Search code examples
javastringint

Int equivalent of string.isempty


I am hoping this is an easy fix. I am after a way to detect that the user has hit the enter key when prompted for an int value. I know the .isEmpty does not work with values declared as int, what is the best way to get around this?

System.out.println("Please enter the first number:");
    user_number1 = input.nextInt();
        if (user_number1.isEmpty){

        }

Solution

  • There is no way for an int to be empty. input.nextInt() will not proceed until the user enters a value that is not whitespace. If it's not an int, it will throw a InputMismatchException. This is documented in the Scanner.nextInt() Javadoc. You can test if there is an int with Scanner.hasNextInt() before trying to consume the next token.

    while (true) {
        System.out.println("Please enter the first number:");
        if (input.hasNextInt()) {
            user_number1 = input.nextInt();
            break;
        } else {
            System.out.println("not an int: " + input.nextLine());
        }
    }