2017-04-01 31 views
0

請參考以下代碼,瞭解在開關塊內哪些循環中斷不起作用,您能幫忙嗎?循環中斷在字符串陣列的開關塊內不起作用

String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" }; 

    //For loop is not breaking after getting the correct value 
    for (int t = 0; t < Books.length; t++) { 
     switch (Books[t]) { 
     case "Harry Potter": 
      System.out.println("Getting from switch case " + t + " " + Books[t]); 
      break; 
     default: 
      System.out.println("Invalid search for book from switch case"); 
      break; 
     } 
    } 
+2

請格式化您的代碼。 – Omore

+0

只要您返回找到的值,使用return的解決方案就會工作,如果循環所在的方法返回void,則在找到和未找到之間沒有區別,您將需要執行額外的檢查,例如檢查找到標誌或for!= null – efekctive

+1

您只有'switch'不是'爲' –

回答

1

那麼,這個突破只會突破switch語句。您可以嘗試使用labeled break,例如

loop: 
for (int t = 0; t < Books.length; t++) { 
    // ... 
    case: 
     // ... 
     break loop; 

或者,您可以將循環放入其自己的方法中,而使用return語句。

+0

非常感謝。它的工作:) – myflash

2

switch聲明符內只使用了交換機流量時break,而不是爲循環,所以 如果你想打破for循環,使用return當正確的價值被發現,這將break循環,從該方法返回,如下所示:

String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" }; 
    for (int t = 0; t < Books.length; t++) { 
     switch (Books[t]) { 
     case "Harry Potter": 
      System.out.println("Getting from switch case " + t + " " + Books[t]); 
      return;//use return when CORRECT CONDITION is found 
     default: 
      System.out.println("Invalid search for book from switch case"); 
      break; 
     } 
    } 

簡單來說,您的break將被應用到內碼塊,其在這裏是switch,因此它不會breakfor的循環。所以,如果你想breakswitch & for在一起,使用return聲明,以便它從方法返回。

很重要的一點是,不使用標籤在這針對結構化編程代碼(線之間跳轉)。

OPTION(2):

如果不從方法要return,你需要重構你的代碼和移動書中發現邏輯像checkBookExists一個單獨的方法,如下圖所示:

private boolean checkBookExists(String book, int t) { 
     boolean bookFound = false; 
     switch (book) { 
     case "Harry Potter": 
      bookFound = true; 
      System.out.println("Getting from switch case " + t + " " + book); 
      break; 
     default: 
      System.out.println("Invalid search for book from switch case"); 
      break; 
     } 
     return bookFound; 
    } 

現在稱之爲checkBookExists方法for循環中,如下圖所示,當書被發現,forbreak

String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" }; 
    for (int t = 0; t < Books.length; t++) { 
     if(checkBookExists(Books[t], t)) { 
      break; 
     } 
    } 
+0

感謝您的解決方案!這也很好 – myflash

+0

我推薦這些選項比標籤,這是不好的做法,這裏看看這裏:http://stackoverflow.com/questions/11133127/why-it-is-a-bad-practice-to-use- break-continue-labels-in-oop-eg-java-c – developer

+0

不錯的解決方案,如果你覺得他的解決方案有用接受它作爲將來的參考 – Oghli