loop break not working inside switch block on array of strings
本问题已经有最佳答案,请猛点这里访问。
请参阅下面的代码,其中循环中断在开关块内不起作用,您能帮忙吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } |
当在
1 2 3 4 5 6 7 8 9 10 11 | 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; } } |
简单地说,您的
一个重要的点是不要在代码中使用标签(在行之间跳转),这与结构化编程相反。
选项(2):
如果不想从方法中删除
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } |
现在调用
1 2 3 4 5 6 | 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; } } |
好吧,这个中断只会从switch语句中断。您可以尝试使用带标签的中断,例如
1 2 3 4 5 6 | loop: for (int t = 0; t < Books.length; t++ ) { // ... case: // ... break loop; |
或者,您可以将循环放入它自己的方法中,并使用返回语句。