Java程序让用户输入相同的输入两次,以在初始输入错误后运行

Java程序让用户输入相同的输入两次,以在初始输入错误后运行,java,while-loop,Java,While Loop,我的程序有问题。但是,当用户输入错误的变量时,它确实会显示正确的反馈,但是用户必须输入一个比前面所述的多的变量 也许这是我犯的一个简单的错误,但我看不出来 这令人困惑。运行程序时的一个示例: How many grades would you like to average? 3 Please enter 3 grades: 90 jf //Intentional user input error You've entered a non-numerical variable. Pleas

我的程序有问题。但是,当用户输入错误的变量时,它确实会显示正确的反馈,但是用户必须输入一个比前面所述的多的变量

也许这是我犯的一个简单的错误,但我看不出来

这令人困惑。运行程序时的一个示例:

How many grades would you like to average? 
3

Please enter 3 grades: 
90
jf //Intentional user input error
You've entered a non-numerical variable. Please enter a number: 
95
100 //The program should go ahead and calculate the average after this is entered
100 //It should not expect this fourth input if the amount of grades is 3

Your average is: 96.67
控制台中的第二个100输入不应出现,但当用户至少有一个输入错误时会出现。如果我运行程序并输入所有正确的变量,那么程序运行起来会很顺利

当询问用户希望平均分数时,也会出现此错误。我想在第二部分可以更容易地看到我的程序有什么问题

我正在努力让这个程序顺利运行。谢谢你的帮助

for (gradesCount = 0; gradesCount < gradeNumber; gradesCount++) {
            // Check if the input variables are numerical variables
            while (!input.hasNextDouble()) {
                input.next();
                System.out.println("You've entered a non-numerical variable. Please enter a number: ");
                while (input.nextInt()<= 0){

                System.out.println("You've entered a negative number. Please eneter a positive number: ");
                }

            }
            // Read grade input
            gradesInput = input.nextDouble();
for(gradeScont=0;gradeScontwhile(input.nextend()而不是
input.hasNextDouble()
您可以在下面尝试

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter total no of input ");
    int total = Integer.parseInt(scan.nextLine());
    int[] input = new int[total];
    for (int i = 0; i < total; i++) {
        while (true) {
            try {
                System.out.print("Enter number ");
                String in = scan.nextLine();
                input[i] = Integer.parseInt(in);
                break;
            } catch (RuntimeException re) {
                System.err.print("Invalid input. ");
            }
        }

    }
    scan.close();
    System.out.println(Arrays.toString(input));
Scanner scan=新的扫描仪(System.in);
系统输出打印(“输入输入的总数量”);
inttotal=Integer.parseInt(scan.nextLine());
int[]输入=新的int[总计];
对于(int i=0;i

它将强制用户只输入数字,如果需要,您可以添加边界或更改数据类型。

谢谢您的输入!但是我的程序的目的之一是向用户反馈初始输入错误的原因。我只想弄清楚为什么用户在输入错误的输入后需要输入两次。检查如果
input[i]>0
则打印不接受输入的原因,而不是
无效输入。
打印
不是从扫描仪中获取的数字
input.next()
input.nextInt()
。您将获得
input.nextInt()
input.next()