我是一名新的Java学生(在家自学),我制作了这个平均计算器,它完美无缺,但我想添加一个条件,阻止用户输入大于100的数字,因为成绩通常在100结束时,我正在努力解决这样做的正确方法。 这是我的代码:
import java.util.Scanner;
class books{
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
int total = 0;
int grade = 0;
int average;
int counter = 0;
System.out.println("Please enter all your grades:");
while(counter < 12){
grade = userInput.nextInt();
total = total + grade;
counter++;
if(grade > 100){
System.out.println("Please enter a valid grade");
}
}
average = total/12;
System.out.println("You average is " + average);
}
}
感谢。
答案 0 :(得分:1)
在使用输入的grade
值之前,您应该对其进行验证,如果它无效,则继续循环:
while(counter < 12){
grade = userInput.nextInt();
if (grade > 100) {
System.out.println("Please enter a valid grade");
} else {
total = total + grade;
counter++;
}
}
此外,在计算多个值的平均值时,进行整数除法并不是一个好主意,因为您可能会得到错误的结果。更好:
double average = 0d;
...
average = total / 12.0;
答案 1 :(得分:0)
解决方案是:
import java.util.Scanner;
class books{
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
int total = 0;
int grade = 0;
int average;
int counter = 0;
System.out.println("Please enter all your grades:");
while(counter < 12){
grade = userInput.nextInt();
if(grade > 100 || grade < 0){
System.out.println("Please enter a valid grade again!");
}else{
total = total + grade;
counter++;
}
}
average = total/12;
System.out.println("You average is " + average);
}
}
归功于Kocko;)