如何使大于100或小于0的数字不能平均添加?脚本编译并运行正常,但当我输入101时,它告诉我数字太大,但仍然取其平均值。谢谢!
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;
if( grade > 100 || grade < 0) {
if ( grade > 100 ) {
System.out.println( "Number too large, enter a new number");
}
if ( grade < 0 ) {
System.out.println( "Number too small, enter a new number");
}
}
System.out.println( "Enter grade or -1 to quit: ");
grade = dylan.nextInt();
}
if ( gradeCounter != 0 )
{
average = (double) total / gradeCounter;
System.out.printf( "Class average is %.2f", average );
}
else
System.out.println( "No grades were entered" );
}
}
答案 0 :(得分:0)
添加continue
以跳到下一个循环迭代。将计算移动到这些检查下方,以便在检查失败时不执行计算。
if ( grade > 100 ) {
System.out.println( "Number too large, enter a new number");
continue;
}
if ( grade < 0 ) {
System.out.println( "Number too small, enter a new number");
continue;
}
total = total + grade;
gradeCounter = gradeCounter + 1;
答案 1 :(得分:0)
您在测试值之前进行平均。将平均代码放在else语句中。
if ( grade > 100 || grade < 0) {
if ( grade > 100 ) {
System.out.println( "Number too large, enter a new number");
}
if ( grade < 0 ) {
System.out.println( "Number too small, enter a new number");
}
} else {
total = total + grade;
gradeCounter = gradeCounter + 1;
}