[英]How to break out of loop when case is selected
我有一個包含4種情況的代碼,我想打破循環,如果選擇了'f'情況。 然后從這種情況下選擇。 當我嘗試執行if語句時遇到30個錯誤,但是當我拿走它時,代碼很好。
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
}
if (case == 'f')
{
break;
}
}
您將使用Java label
(請參見名為BreakWithLabelDemo.java的此代碼示例)來告訴您的代碼在何處break
。
myloop:
while ( true ){
switch( choice ){
case 'f':
friendsList();
break myloop;
}
}
對於您的實現,有意義的是在進入switch語句之前就中斷特定情況。 例如:
char choice = one.charAt(0);
if (choice == 'f') break;
switch(choice)
這似乎是退出while循環而不與switch語句的break語句沖突的一種非常簡單的方法。
或者,如果在choice
為'f'
時仍需要調用friendsList方法,則可以將該if語句移至switch語句之后。
注意:與此同時,您還應該刪除代碼示例底部的if語句。
if (case == 'f')
這句話是什么情況? 您應該將其替換為選擇。
if (choice == 'f')
您需要在while循環中放入if。
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
if (choice == 'f')
{
break;
}
}
如果將if語句移至while循環內部才能生效,而將if語句內的case更改為choose。
所以
While(yea==true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
if(choice == 'F')
{
break;
}
switch(choice)
{
//cases
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.