[英]Why is the Java scanner skipping over one of the user prompt in a while statement, nested in the for loop?
掃描程序不會在第二個while語句中提示用戶輸入,該語句嵌套在for循環中。 為什么? 有什么辦法嗎?
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
循環,因為您希望循環始終在第一次運行,但是您還希望在循環結束時檢查條件。
更改
while((credits < 0) || (credits < 9))
至
while((credits < 0) || (credits > 9))
旁注:“包含”表示您希望將0和9包括為允許的信用值。 但這不是這里的內容,因為您使用的是<而不是<=和>而不是> =。
將其更改為while((credits <= 0)||(credits> 9)),因為您已將信用額初始化為'0'。只需添加
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");
}
if(credits == 0)
break;
// gpas.addTotals(grade, credits);
}
學分將接受0-9,並且不會再次詢問用戶
我試圖修改last while循環以適合您的需求,希望這段代碼對您有所幫助。
do {
System.out.print("Enter credits: ");
credits = in.nextInt();
if ((credits < 0) || (credits > 9)) {
System.out.println("Invalid credits - must be between 0 and 9");
}else{
gpas.addTotals(grade, credits);
}
} while ((credits < 0) || (credits > 9));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.