gpt4 book ai didi

java - 嵌套控制结构,平均脚本

转载 作者:行者123 更新时间:2023-12-02 06:13:25 25 4
gpt4 key购买 nike

使用嵌套控制结构编写脚本,对 0 到 100 之间的任何数字进行平均,如果任何数字高于 100 或低于 0,则会产生错误。

import java.util.Scanner;

public class ExerciseSix
{
public static void main( String[] args )
{

Scanner dylan = new Scanner(System.in);

int gradeCounter;
int total;
int grade;
double average;

total = 0;
gradeCounter = 0;

System.out.println( "Enter a grade or -1 to quit: " );
grade = dylan.nextInt();

while ( grade != -1 )
{

total = total + grade;
gradeCounter = gradeCounter + 1;





System.out.println( "Enter grade or -1 to quit: ");
grade = dylan.nextInt();


if ( grade > 100 );
System.out.println( "Number too large");

if ( grade < 0 );
System.out.println( "Number too small");
}


if ( gradeCounter != 0 )

{

average = (double) total / gradeCounter;


System.out.printf( "Class average is %.2f", average );



}

else
System.out.println( "No grades were entered" );

}

我没有收到任何编译错误,但是当我输入数字时,第一个数字会正确输入。然后无论我输入 0 到 100 之间的哪个数字,它都会显示

“5 数量太大 数量太小 输入成绩或 -1 退出:“

我认为大量数字也被添加到平均值中

最佳答案

删除 if 语句中的分号

改变

if ( grade > 100 );
System.out.println( "Number too large");

if ( grade < 0 );
System.out.println( "Number too small");

if ( grade > 100 )
System.out.println( "Number too large");

if ( grade < 0 )
System.out.println( "Number too small");

最佳实践是将所有 if 语句用大括号括起来,这样就不会出现任何意外行为

if ( grade > 100 ){
System.out.println( "Number too large");
}

对于要添加到总数中的大数字,您需要在计算之前进行数据验证,即

while(grade != -1){
if( grade > 100 || grade < 0) {
//Message
}
else{
//Total calculation
}
}

关于java - 嵌套控制结构,平均脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com