简体   繁体   English

无法弄清楚为什么我的程序不起作用

[英]Can't figure why my program doesnt work

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);

}

} }

So it's totally a simple program where it asks the user to input points for 5 judges in total and then sums up the points at the end. 因此,这是一个完全简单的程序,它要求用户总共输入5位法官的分数,然后在最后汇总分数。 But points can only be inserted between 0-20, if it goes outside of the range, it gives an error telling us to input again and continues to do so until we have give a valid input. 但是点只能插入0到20之间,如果超出范围,则会出现错误,告诉我们再次输入,并继续这样做,直到输入有效的输入为止。

Now the program works pretty well except for a point that if I enter "22" for example, it asks again like intended but if I enter "22" once again, it lets it pass and skip to next judge. 现在该程序运行良好,除了例如我输入“ 22”时,它再次按预期方式询问,但如果我再次输入“ 22”,则它使它通过并跳至下一个判断。

How can I make it to keep asking until I have given a valid input before it moves to next judge? 在我提供有效输入之前,如何使它继续询问,然后再移交给下一位法官? Please give a small explanation if you fix my code. 如果您修复我的代码,请给一个小小的解释。

Also I'm supposed to make a small edit that when it sums up the points at the end, it minus the highest and lowest score away, summing up only the points between. 另外,我应该做一个小的编辑,当它最后总结点时,减去最高和最低分数,只对它们之间的点求和。 So if the points are "3,5,8,9,20" it will take "3 and 20" away and only sums up "5,8 and 9" making it 22. 因此,如果点是“ 3,5,8,9,20”,它将带走“ 3和20”,并且仅将“ 5,8和9”加起来就等于22。

In your code, you have an if statement to check the input, but if your input doesn't pass your program will accept your next input without checking it. 在您的代码中,您有一个if语句来检查输入,但是如果您的输入未通过,则程序将接受您的下一个输入而不进行检查。

To fix this, don't progress your program until your input is valid using a while loop, like this: 要解决此问题,请使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM