[英]Why is my switch statement not working and stuck in an infinite loop?
我試圖讓它輸出用戶的財富,但是它只會輸出用戶無限輸入的數字。
我究竟做錯了什么? 如何解決無限循環?
public static void main(String[] args) {
Scanner broncos = new Scanner ( System.in );
int x, y, a;
System.out.println("Would you like me to tell your fortune? Type 1 for yes and any other number for no: ");
x = broncos.nextInt();
while (x==1)
{
System.out.println("Enter a number from 1-8: ");
y = broncos.nextInt();
while ( y > 0 && y < 9)
System.out.println( y );
System.out.print ( "That's not a valid number. Try again. ");
y = broncos.nextInt();
}
System.out.println ("Enter a number from 1-8: ");
a = broncos.nextInt();
switch (a)
{
case 8 :
System.out.println ("You will win the lottery" );
break;
case 7 :
System.out.println ("You are going to do great things");
break;
case 6 :
System.out.println ("Don't get out of the house today");
break;
case 5 :
System.out.println ("You'll get a raise at work");
break;
case 4 :
System.out.println ("Lucky day today");
break;
case 3 :
System.out.println ("Not so lucky day today");
break;
case 2 :
System.out.println ("Your favorite sports team will win" );
break;
case 1 :
System.out.println ("Your car is going to break down" );
break;
default:
System.out.println ( "You didn't enter 1-8!" );
}
broncos.close();
}
引起問題的不是您的switch語句,而是while循環優先。 您可以像while (x==1)
一樣測試x
,但是在while循環中在哪里更改x
? 如果您從不更改x
的狀態,則測試將永遠不會變為假,並且循環將永遠不會退出。
正如湯姆敏銳指出的那樣,您將需要while循環來驗證y
輸入,以封裝與獲取y輸入有關的所有代碼。
while ( y > 0 && y < 9) {
System.out.println("Enter a number from 1-8: ");
y = broncos.nextInt();
if (y > 0 && y < 9) {
System.out.println( y );
System.out.print ( "That's not a valid number. Try again. ");
}
}
現在,在switch語句中使用正確的y
。
另外,一旦您有一個正確的y
,就無需獲取a
:
// System.out.println ("Enter a number from 1-8: ");
// a = broncos.nextInt();
同樣,只需在switch語句中使用y
。
至於x
,則無需驗證它(除非您需要檢查它是否是一個數字),因為輸入的任何數字都可以使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.