while while循环重复两次,不遵循条件

时间:2017-10-28 16:02:36

标签: java do-while repeat

我是Java的新手,我遇到了一些问题。我的教练要求我在while循环中嵌入do while循环; do while循环为中期,最终和项目成绩的用户可以输入的等级类型(大于0但小于100)创建限制。然后将该输入用于计算这三个等级的平均值。

但是,我的do while循环运行两次并在计算中使用第二个提示输入的平均值。我究竟做错了什么?我已经浏览了我的教科书和本网站,但我似乎无法理解为什么要这样做,因为它只提示两次然后只使用输入进行第二次提示。任何帮助将不胜感激。感谢您抽出宝贵时间阅读我的帖子!

为了澄清,这是我的代码:

System.out.println("******** Step 2: Grading for Multiple Students *********");
    System.out.println();
    // Create scanner object for text and number
    Scanner textReader = new Scanner(System.in);
    Scanner numberReader = new Scanner(System.in);
    System.out.print("Would you like to input grades (y/n): ");
    String response = textReader.nextLine();
    // Create while loop for first yes/no question
    while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
    {
        System.out.print("y/n needed: ");
        response = textReader.nextLine();
        System.out.println();
    }
    while ((response.equalsIgnoreCase("y")))
    {
        System.out.print("\nStudent Name: ");
        String studentName = textReader.nextLine();
        System.out.print("Course Name: ");
        String courseName = textReader.nextLine();
        System.out.print("Midterm Grade (needs to be between 0-100): ");
        double midtermGrade = numberReader.nextDouble();
        do
        {
            System.out.print("Midterm Grade (needs to be between 0-100): ");
            midtermGrade = numberReader.nextDouble();
            break;
        }
        while ((midtermGrade < 0) || (midtermGrade > 100));
        System.out.print("Final Grade (needs to be between 0-100): ");
        double finalGrade = numberReader.nextDouble();
        do
        {
            System.out.print("Final Grade (needs to be between 0-100): ");
            finalGrade = numberReader.nextDouble();
        }
        while ((finalGrade < 0) || (finalGrade > 100));
        System.out.print("Project Grade (needs to be between 0-100): ");
        double projectGrade = numberReader.nextDouble();
        do
        {
            System.out.print("Project Grade (needs to be between 0-100): ");
            projectGrade = numberReader.nextDouble();
        }
        while ((projectGrade < 0) || (projectGrade > 100));

这是我的输出:

Output link

1 个答案:

答案 0 :(得分:1)

在do-while循环中,无论条件如何,都至少调用一次循环。 在正常的while循环中,仅在满足条件时才调用循环。

而不是

System.out.print("Final Grade (needs to be between 0-100): "); // remove this
double finalGrade = numberReader.nextDouble(); // remove this
do
{
   System.out.print("Final Grade (needs to be between 0-100): ");
   finalGrade = numberReader.nextDouble();
}
while ((finalGrade < 0) || (finalGrade > 100));

只需删除每个输入循环的上述代码段的前两行。