[英]How do I fix this Java Loop Scanner
這是我正在運行的代碼的一部分,當代碼運行時它讓我輸入一個數字但不會讓我繼續,它只會繼續打印“輸入學生的總測驗分數:”即使我輸入了價值不及滿分求助!
while (perfectQuizScore > quizScore ) {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
}
OUTPUT:在此處輸入圖片描述
如果我正確理解你的問題......你想在提供的測驗分數小於(或等於)滿分時退出循環? 如果是這樣,您只需要更改 while 循環條件中的符號(它當前正在檢查大於)。
之前: while (perfectQuizScore > quizScore ) {
之后: while (perfectQuizScore < quizScore ) {
現在假設您最初將quizScore
設置為一個巨大的值(如果您將其初始化為0
,則條件將在進入循環之前評估為 false)。 更好的解決方案可能是使用do-while
循環。
int quizScore = 0;
do {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
} while (perfectQuizScore < quizScore or quizScore < 0);
盡管我個人可能會以不同的方式構建它,以避免兩次寫下你的“壞”條件:
int quizScore = 0;
while (True) {
System.out.print("Enter a student's total quiz score : ");
quizScore = Integer.parseInt(keyboard.nextLine()); // 6
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore < 0) {
System.out.println("Invalid value! Value must be greater than 0.");
}
else {
// good input, exit the loop with a break statement
break;
}
}
也許以下是您要搜索的內容:
do {
System.out.print("Enter a student's total quiz score : ");
quizScore = scnr.nextInt();
if (quizScore > perfectQuizScore) {
System.out.println("Invalid value! Score must not be greater than perfect score.");
}
else if (quizScore <= 0) {
System.out.println("Invalid value! Value must be greater than 0.");
} else {
break; // get out of the loop
}
} while ( quizScore <= 0 || quizScore > perfectQuizScore );
第一次獲取后進行檢查( while
),同時更改檢查以保持循環直到用戶寫入有效值。
do {...}
會讓里面的代碼在while
檢查之前運行一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.