Java Arena
Step 1 of 5

while (true) and break

A loop runs the same lines again and again. The simplest loop in Java is while (true): the block after it repeats forever, until a break inside it ends the loop.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("Type a word (end stops):");
            String word = scanner.nextLine();
            if (word.equals("end")) {
                break;
            }
            System.out.println("You typed " + word);
        }
        System.out.println("Bye!");
    }
}
Input
cat
dog
end
Output
Type a word (end stops):
You typed cat
Type a word (end stops):
You typed dog
Type a word (end stops):
Bye!

Each time round, the loop asks, reads a word and checks it. For cat and dog it prints the word and starts again from the top. For end, break jumps straight out of the loop, to the first line after its closing }.

A while (true) loop needs a way out. Here the input is the way out: if it never contains end, the loop keeps reading until the input runs out, and the program crashes with a NoSuchElementException ("No line found"): it asked for more input than it was given. A loop that doesn't read anything and has no break would never stop at all; on this site such a program is stopped after 10 seconds, with a note that it probably has an endless loop.

Your task

Challenge 1 of 3

Fill in the blanks, so the loop keeps reading until the password is open sesame. For the input abracadabra and then open sesame the program prints:

The door stays shut.
The door opens!

Challenge 2

A lift reads floor numbers. For each one it prints Going to floor X, until the number is 0: then it prints Back on the ground floor and stops. Use a while (true) loop and leave it with break. For the input 3, 5 and 0 the program prints:

Going to floor 3
Going to floor 5
Back on the ground floor

Challenge 3

A weather station reads temperatures. A reading below -50 or above 60 means the sensor is broken. Print each normal reading as Reading: X; at the first broken one, print Sensor error and leave the loop with break. For the input 12, 15 and 99 the program prints:

Reading: 12
Reading: 15
Sensor error