How to insist that a users input is an int?

45,762

Solution 1

Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.

In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.

Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
    scan.next();
}
int input = scan.nextInt();

Solution 2

Here's a simple example with prompts and comments.

Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input

// Repeat until next item is an integer
while (!scan.hasNextInt()) 
{        
    scan.next(); // Read and discard offending non-int input
    System.out.print("Please enter an integer: "); // Re-prompt
}

// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer

// And now you can use the input variable.

Solution 3

I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.

The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.

You can test the program here.

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean inputAccepted = false;
        while (!inputAccepted) {
            try {
                System.out.print("Please enter a number: ");
                Integer.valueOf(input.nextLine());
                inputAccepted = true;
            } catch (NumberFormatException e) {
                System.out.println("Not a valid number.");
            }
        }
        System.out.println("Thank you!");
    }
}

Solution 4

Use scan.hasNextInt() to make sure the next input is an int.

Share:
45,762
John Smith
Author by

John Smith

Updated on April 20, 2020

Comments

  • John Smith
    John Smith about 4 years

    Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.

    I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:

        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();
    

    And continue on with my program, and everything works fine.

    Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).

    How can I make the code more robust, where it would verify that only an int was entered?

    These are the results I'm hoping for:

    Lets say the input was:

    23 -> valid
    fx -> display an error message, ask the user for input again (a while loop would do..)
    7w -> error, again
    3.7 -> error
    $$ -> error
    etc
    
  • Bohemian
    Bohemian over 11 years
    -1 If the user enters a non-integer, your code will hang and never recover: scanner.hasNextInt() does not advance past input, and if the next input is a non-int, scanner.hasNextInt() will always return false, even if the user later enters an integer
  • Bohemian
    Bohemian over 11 years
    If the user enters a non-integer, your code will hang and never recover: scanner.hasNextInt() does not advance past input, and if the next input is a non-int, scanner.hasNextInt() will always return false, even if the user later enters an integer
  • ignis
    ignis over 11 years
    @Bohemian: True, thank you, I've corrected the code to discard non-int inputs.
  • Mordechai
    Mordechai over 11 years
    @Bohemian I didn't give any suggestions how to use it, you just copied this from ignis...
  • John Smith
    John Smith over 11 years
    I think you meant to write scan, not scanner, in the while loop (twice), but otherwise, thank you!
  • Peopleware
    Peopleware about 11 years
    The OP asked for non-code explanations. Besides this code is not handling any exception.