简体   繁体   中英

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){

        }

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());
    }
}

As @Elliott Frisch's answer states, the .nextInt() call is just not going to return until an actual number of some sort is entered (or, if something else is submitted by the user, the InputMismatchException occurs instead.

One easy alternative is to just.. not call .nextInt() then. call .next() , check if the resulting String is empty, and if not, turn it into an integer using: int userNumber = Integer.parseInt(theStringYouGotFromScannerNext); .

NB1: Java convention states a variable is named 'userNumber1', not 'user_number1'. When in Rome and all that.

NB2: If you want your scanner to read 1 answer every time the user presses enter, call scanner.useDelimiter("\r?\n"); immediately after new Scanner . Out of the box it gives you 1 answer per whitespace which is usually not what you want in the first place.

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){

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM