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之间插入点,如果它超出范围,则会给出错误,告诉我们再次输入并继续这样做,直到我们给出有效输入。
现在该程序运作良好,除非我输入&#34; 22&#34;例如,它再次按照预期要求,但如果我输入&#34; 22&#34;再一次,它让它通过并跳到下一个判断。
如果在进入下一个裁判之前我已经提供了有效的输入,我怎么能让它继续询问?如果你修改我的代码,请给出一个小的解释。
此外,我应该做一个小编辑,当它总结最后的点数时,它减去最高和最低分数,仅总结两者之间的分数。所以,如果积分是&#34; 3,5,8,9,20&#34;它需要&#34; 3和20&#34;离开,只总结了#8; 5,8和9&#34;制作它22。
答案 0 :(得分:1)
在你的代码中,你有一个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;
}