gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:04:34 24 4
gpt4 key购买 nike

我是 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

最佳答案

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

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

关于java - do while 循环重复两次,不遵循条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46991707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com