有人可以向我解释我如何才能提出等级的条件,只能是0或更高或100或更低。我已经尝试了while循环中的语句,但是平均值不正确。我把它放在循环之外,但这似乎也不起作用。
while (!gradeInput.equals(SENTINEL)) {
try {
int grade = Integer.parseInt(gradeInput);
sum += grade;
count++;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Error! only numeric values.");
}
gradeInput = JOptionPane.showInputDialog("Enter exam grade (or -1 to end the program):");
}
答案 0 :(得分:1)
Sharma的评论可能更清晰,但这也应该有效:
gradeInput计算应该在循环的开头 - 而不是结束。
然后将您的验证放在循环中(如果输入有效,则只进行求和和计数)
if(grade>0 && grade <100) {
sum += grade;
count++;
}
然后用和/计算
计算循环外的平均值答案 1 :(得分:0)
while (!gradeInput.equals(SENTINEL)) {
try {
int grade = Integer.parseInt(gradeInput);
if(grade==0 || grade<=100){
sum += grade;
count++;
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Error! only numeric values.");
}
gradeInput = JOptionPane.showInputDialog("Enter exam grade (or -1 to end the program):");
}
答案 2 :(得分:0)
试试这个
while (!gradeInput.equals(SENTINEL)) {
try {
int grade = Integer.parseInt(gradeInput);
if(grade>=0 && grade<=100){
sum += grade;
count++;
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Error! only numeric values.");
}
gradeInput = JOptionPane.showInputDialog("Enter exam grade (or -1 to end the program):");
}