简体   繁体   中英

Do-While loop on user input - check if input is not empty or int (java)

I want the user to be repeatedly asked a question if the user input is either empty OR not an int. This is what I have so far:

        Scanner scn = new Scanner(System.in);
        do {
            System.out.print("Enter id: ");
            int id = scn.nextInt();
         } while (!scn.hasNextInt());

简单地说:

while (scanner.hasNextInt());

Try something like this:

boolean running = true;

while(running){
    String s = scn.nextLine();
    if(!(s!=""||isInt(s))){
        running = false;
    }
}

You need to implement your own isInt() function, but some google will give you this.

Try this removing ! :

while (scn.hasNextInt());

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