The effect of the break statement is to terminate the current loop, whether it be a while, for, for-each, or do-while statement. It is also used in the switch statement. The break statement passes control to the next statement following the loop. The break statement consists of the break
keyword.
Consider the effect of the following statement sequence which repeatedly prompts the user for a command within an infinite loop. The loop will be terminated when the user enters the Quit
command:
String command; while (true) { System.out.print("Enter a command: "); Scanner scanner = new Scanner(System.in); command = scanner.next(); if ("Add".equals(command)) { // Process Add command } else if ("Subtract".equals(command)) { // Process Subtract command } else if ("Quit".equals(command)) { break; } else { System.out.println("Invalid Command"); } }
Notice how the equals
method is used. The equals
method is executed against the string...