break
when used inside the switch
statement breaks ONLY the switch flow, but not the for loop, so
If you wanted to break the for
loop, use return
when the correct value is found which will break
the loop and returns from the method, as shown below:
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;
}
}
In simple terms, your break
will be applied to the inner code block which is a switch
here, so it doesn't break
the for
loop. So, if you wanted to break
both switch
& for
together, use return
statement so that it returns from the method.
One important point is that do not use the labels (to jump between lines) in the code which is against to the structured programming.
OPTION(2):
If you don't want to return
from the method, you need to refactor your code and move the book finding logic to a separate method like checkBookExists
as shown below:
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;
}
Now call that checkBookExists
method inside the for
loop as shown below and when the book is found, for
will break
.
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;
}
}