扫描器不会提示用户在嵌套在 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/