2014-10-30 31 views
0

我有一個代碼,有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; 
    } 
} 
+0

那麼一,大括號不匹配,但你爲什麼不發表您的錯誤訊息? – DreadHeadedDeveloper 2014-10-30 03:57:43

+0

我想if語句擺脫while循環需要在while循環中。 – 2014-10-30 04:08:19

回答

1

你會使用Java label(見命名BreakWithLabelDemo.java此代碼示例)告訴你的代碼在哪裏break

myloop: 
    while (true){ 
     switch(choice){ 
      case 'f': 
       friendsList(); 
       break myloop; 
     } 
    } 
+1

一個鏈接可能對API或示例有幫助 – DreadHeadedDeveloper 2014-10-30 03:58:39

+0

對不起,我在提交之前粘貼了我的代碼示例 – doublesharp 2014-10-30 03:59:27

0
if (case == 'f') 

是什麼情況,這種說法?你應該選擇替換它。

if (choice == 'f') 
1

對於您的實現,在輸入switch語句之前打破特定情況是有意義的。例如:

char choice = one.charAt(0); 

if (choice == 'f') break; 

switch(choice) 

這似乎是一個非常簡單的方式來退出while循環,而不會與switch語句的break語句發生衝突。

或者如果在choice'f'時仍然需要調用friendsList方法,則可以將if語句移至switch語句後面。

注意:有了這個,你還應該刪除代碼示例底部的if語句。

0

如果需要在while while循環中放置。

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; 
     } 

    } 
0

if語句應該在while循環內部移動才能生效,並且if語句中的case應該改爲choice。

所以

While(yea==true) 
    { 
     System.out.print(MENU); 
     one = sw.next(); 
     char choice = one.charAt(0); 

     if(choice == 'F') 
     { 
       break; 
     } 
     switch(choice) 
     { 
      //cases   
     } 
}