java - 为什么 Java 扫描器会跳过嵌套在 for 循环中的 while 语句中的用户提示符之一?

标签 java

扫描器不会提示用户在嵌套在 for 循环中的第二个 while 语句中进行输入。为什么?有什么解决办法吗?

   import java.util.Scanner;

    public class ComputeGpa
    {
        public static void main(String args[])
        { 
            char grade = '\0';
            int credits = 0;
            String aGrade = "";

            Scanner in = new Scanner(System.in);

            Gpa gpas = new Gpa();

            int numCourses = 0;
            while(numCourses <= 0)
            {
                System.out.print("Enter number of courses: ");
                numCourses = in.nextInt();
                if(numCourses <= 0)
                {
                    System.out.println("Invalid number of courses - must be greater than 0!");
                }
            }

            for(int i = 0; i < numCourses; i++)
            {
                while(aGrade.length() != 1)
                {
                    System.out.print("Enter grade (one character): ");
                    aGrade = in.next();
                    grade = aGrade.charAt(0);
                    if(aGrade.length() != 1)
                    {
                        System.out.println("Invalid grade - must be exactly one character");
                    }
                }

                while((credits < 0) || (credits > 9))// this is the while statement I have
                    problems with
                    {
                    System.out.print("Enter credits: ");
                    credits = in.nextInt();
                    if((credits <  0) || (credits > 9))
                    {
                        System.out.println("Invalid credits - must be between 0 and 9");
                    }
                    gpas.addTotals(grade, credits);
                    }
            }

            System.out.printf("GPA: %.2f", gpas.calcGpa()); 

        }        
    }

我尝试验证的条件是用户必须输入 0 到 9 之间的数字(含 0 和 9)。

然后我得到一个计算值“NaN”

最佳答案

while 循环更改为 do ... while 循环,因为您希望循环始终在第一次运行,但您也希望条件在循环结束时进行检查。

关于java - 为什么 Java 扫描器会跳过嵌套在 for 循环中的 while 语句中的用户提示符之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19648970/

相关文章:

java - OnClick 方法杀死 Android 应用程序

Java 覆盖注解的默认值

java - 从 servlet 调用映射作业时出错

java - JDBC:Oracle 存储过程返回嵌套表

java - 实例变量的值在两个类中是不同的。为什么? (+更多问题)

java - 从另一个类以编程方式关闭抽屉导航

java - 测试应用程序是否在 Java 的 jar 文件中运行

java - Android 使用 Firebase Build APK 工作正常,但发布 APK 崩溃

java - 如果我只有类的对象,如何覆盖类的行为?

java - 忽略字符串中的数字