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!

Shail
  • 881
  • 9
  • 20
  • 37

5 Answers5

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");
            }
        }
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • @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! – Juned Ahsan Oct 02 '13 at 05:19
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();

}
boxfish
  • 135
  • 7
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);
        }
    }
}
Shail
  • 881
  • 9
  • 20
  • 37
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();
Ava_Katushka
  • 144
  • 8
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");
    }
Niki
  • 1,105
  • 1
  • 10
  • 17