Skip to content

How can I check if the user input is a string

I’m trying to check if the user inputs a string. If the user inputs a string, my program should output an error message. If the user enters an integer my program should proceed with the program

Here’s my code so far, I need to add another condition to check if the user inputs string, I tried some methods but they don’t work

public int UserInput() {
    boolean Continueasking = true;
    int Input = 0;
    while (Continueasking) {
        Input = io.nextInt();
        if (Input == 1 || Input==2 || Input==3) {
            Continueasking = !Continueasking;
        } else {
            System.out.println("try again");
        }
    }
    return Input;

Answer

nextInt() parses user input as an integer. If the user input can’t be parsed as an integer, it throws InputMismatchException. You can catch this exception and handle it as you see fit.

while (continueAsking) {
    try {
       input = io.nextInt();
    } catch (InputMismatchException ex) {
       // invalid input - handle exception
    }
}