Get an integer from the user

You can use scanner to get a string from the user, then try parsing the string to an int data type using a try/catch statement. The program will try to parse the string into an integer, and if it can be done (valid integer) it prints out the input and integer.

If it can't parse the integer, the program runs the "catch" statement and recursively calls the getAndCheckInt method until the user enters a valid integer.

import java.util.Scanner;

public class main { public int getAndCheckInt() { int x = 0; Scanner ans = new Scanner(System.in); System.out.println("Please enter an integer: "); String input = ans.nextLine(); try {

        x = Integer.parseInt(input);
        System.out.println("Valid integer: " + x);
        return x;
    }
    catch(NumberFormatException e){  
        getAndCheckInt();

      }  
    return x;
}

public static void main(String args[]) {

main n = new main();

n.getAndCheckInt();

}

}

Test cases:

Please enter an integer: 

a Please enter an integer: 2 Valid integer: 2

/r/learnjava Thread