import java.util.Scanner;
public class pointSystem {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int points;
int total = 0;
final int judges = 5;
System.out.println("Give points: ");
for(int i=0;i<judges;i++)
{
System.out.println("Give judge's "+ (i+1) + " points: ");
points = scanner.nextInt();
if(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
System.out.println("Total points are "+total);
}
}
所以这完全是一个简单的程序,它要求用户输入总共 5 个评委的分数,然后在最后总结分数。但点只能插入0-20之间,如果超出范围,就会报错,告诉我们重新输入,并继续输入,直到我们给出有效的输入。
现在程序运行得很好,除了一点,例如,如果我输入“22”,它会像预期的那样再次询问,但如果我再次输入“22”,它会让它通过并跳到下一个判断。
如何才能让它继续询问,直到我给出有效的输入,然后再移至下一个法官?如果您修复我的代码,请给出一个简短的解释。
另外,我应该做一个小的编辑,当它总结最后的分数时,它减去最高和最低分数,只总结之间的分数。因此,如果点数是“3,5,8,9,20”,则会去掉“3 和 20”,仅将“5,8 和 9”相加,得到 22。
最佳答案
在您的代码中,您有一个 if 语句来检查输入,但如果您的输入未通过,您的程序将接受您的下一个输入而不进行检查。
要解决此问题,请在使用 while 循环输入有效之前不要继续运行程序,如下所示:
while(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
关于java - 不明白为什么我的程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22748161/