当条件被破坏时,While 循环不会结束

问题描述 投票:0回答:1

我试图要求用户输入一个整数并重复输入更多,直到他们输入-1。

while (UserInput != -1)
        {
            System.out.print("Grade " + count + ": ");
            UserInput = scan.nextInt();
            Grades[arrayCount] = UserInput;
            count ++;
            arrayCount ++;
        }

这是我的循环代码,但输入 -1 后,系统不断要求输入。它甚至不再说打印行了。我希望它在输入 -1 时结束循环。

我尝试将条件设置为 UserInput != -1 且 UserInput >= 0。如果我输入 -1,它会停止使用打印行,但会继续要求输入。

This is the whole thing. 
   import java.util.Scanner;
public class GradeArray
{
   public static void main (String[]args)
   {
       int UserInput = 0;
       int x, count = 1, count2, below = 0, above = 0;
       int arrayCount = 0, averageCount = 0;
       float sum = 0, lavg = 0, havg = 0;
       float avg, HL;
       Scanner scan = new Scanner(System.in);
       
       int[] Grades = new int[100];
       
       System.out.println("Welcome to the grade average program.");
       System.out.println("Enter -1 after the last grade.");
       
       while (UserInput != -1)
       {
           System.out.print("Grade " + count + ": ");
           UserInput = scan.nextInt();
           Grades[arrayCount] = UserInput;
           count ++;
           arrayCount ++;
       }
       
       while (Grades.length >= averageCount)
       {
           sum = Grades[averageCount] + sum;
       }
       
       avg = sum / Grades.length; // reg avg
       System.out.println(count + " grades. Average Grade: " + avg);
       
       // below avg grades
       for (count2 = 0; count2 <= Grades.length; count2 ++)
       {
           if (Grades[count2] < avg)
           {
               below ++;
               lavg = Grades[count2];
           }
       }
       lavg = lavg / below;
       System.out.println(below + " below average grades. Low average: " + lavg);
       // above avg grades
       for (count2 = 0; count2 <= Grades.length; count2 ++)
       {
           if (Grades[count2] < avg)
           {
               above ++;
               havg = Grades[count2];
           }
       }
       havg = havg / above;
       System.out.println(above + " above average grades. High average: " +havg);
       HL = havg - lavg;
       System.out.println("High - Low: " + HL);
   }
}
java arrays while-loop java.util.scanner
1个回答
0
投票

紧接其后的 while 循环是一个无限循环。我试图修复错误的循环。谢谢你的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.