5

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!

5 Answers 5

11

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");
            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

@Shail There may be better solutions available but this is the one i can create using my limited abilities. Accept the answer in case it helped. Thanks!
7

Shorter solution. Just take input in sc.next()

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

}

Comments

6

Working on Juned's code, I was able to make it shorter.

int getInt(String prompt) {
    System.out.print(prompt);
    while(true){
        try {
            return Integer.parseInt(new Scanner(System.in).next());
        } catch(NumberFormatException ne) {
            System.out.print("That's not a whole number.\n"+prompt);
        }
    }
}

Comments

1

Keep gently scanning while you still have input, and check if it's indeed integer, as you need:

String s = "This is not yet number 10"; 
  
        // create a new scanner 
        // with the specified String Object 
        Scanner scanner = new Scanner(s); 
  
        while (scanner.hasNext()) { 
  
            // if the next is a Int, 
            // print found and the Int 
            if (scanner.hasNextInt()) { 
                System.out.println("Found Int value :"
                                   + scanner.nextInt()); 
            } 
  
            // if no Int is found, 
            // print "Not Found:" and the token 
            else { 
                System.out.println("Not found Int value :"
                                   + scanner.next()); 
            } 
        } 
        scanner.close();

Comments

0

As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.

Building up on Juned's code, you can replace try block with an if condition:

    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;
            if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
                System.out.println("Correct input, exit");
                    break;
            }
            System.out.println("Input is not a number, continue");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.