Java 17 do-while loop of user input with switch statement

In this program, you can see Java 17 multi-string (inputMessage) creating BufferedReader to read the user input (System.in). The user input inside the do-while loop will be checked and repeated until the user writes exit. For every input 1, 2, or 3 there is an specific output, but for other user inputs we get the message: “Invalid input. Valid inputs 1, 2, 3 or ‘exit’ Please try again“.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainClassInputWhileTest {
    public static void main(String[] args) throws IOException {
        // Java 17 multiline string
        String inputMessage = """
                Please enter number from 1 - 3 or write 'exit' to stop the program.
                1 get sandwich
                2 get pizza
                3 get water
                """;
        System.out.println(inputMessage);
        // BufferedReader is created in try-with-resources. It will be closed automatically
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            String line;
            do {
                // Read every time user input in the beginning
                line = reader.readLine();
                // line will be checked. If it is different from 1,2,3 or "exit" it will print
                // "Invalid input. Please try again"
                // Switch in Java 17 with Lambda expressions
                String command = switch (line) {
                    case "1" -> "Here is your sandwich";
                    case "2" -> "Here is your pizza";
                    case "3" -> "Here is your water";
                    case "exit" -> "exit";
                    default -> "Invalid input. Valid input 1, 2, 3 or 'exit' Please try again";
                };
                System.out.println("The command is: " + command);

                // do again the cycle if the user input is not "exit"
            } while (!"exit".equals(line));
        }
        // Printing final message
        System.out.println("The program exit! Goodbye!");
    }
}

Console output:

Please enter number from 1 - 3 or write 'exit' to stop the program.
1 get sandwich
2 get pizza
3 get water

1
The command is: Here is your sandwich
2
The command is: Here is your pizza
3
The command is: Here is your water
4
The command is: Invalid input. Valid input 1, 2, 3 or 'exit' Please try again
a
The command is: Invalid input. Valid input 1, 2, 3 or 'exit' Please try again
exit
The command is: exit
The program exit! Goodbye!

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.