Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop user input until an integer is inputted?

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.

int getInt(String prompt){
        System.out.print(prompt);
        Scanner sc = new Scanner(System.in);
        while(!sc.hasNextInt()){
            System.out.println("Enter a whole number.");
            sc.nextInt();
        }
        return sc.nextInt();
}

Thanks for your time!

like image 234
Shail Avatar asked Oct 02 '13 04:10

Shail


People also ask

How do you input an integer as a user?

To use them as integers you will need to convert the user input into an integer using the int() function. e.g. age=int(input("What is your age?")) This line of code would work fine as long as the user enters an integer.

How do you take input until Enter is pressed in Java?

You take a String from user (a single line of numbers) and you split it by space, so you have all the numbers as String in the array. Then you have to parse them to int or do whatever you want with them. Save this answer.

How do you use a while loop for input validation?

To validate input in a while loop: Use a try/except or an if/else statement to validate the input. If the input is invalid, use a continue statement to continue to the next iteration. If the input is valid, use a break statement to break out of the loop.


1 Answers

Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue. Try this:

        System.out.print("input");
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("Enter a whole number.");
            String input = sc.next();
            int intInputValue = 0;
            try {
                intInputValue = Integer.parseInt(input);
                System.out.println("Correct input, exit");
                break;
            } catch (NumberFormatException ne) {
                System.out.println("Input is not a number, continue");
            }
        }
like image 61
Juned Ahsan Avatar answered Oct 24 '22 15:10

Juned Ahsan