扫描器不会在嵌套在 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”的计算值