简体   繁体   中英

How do I get this try catch to loop until it no longer gets an error?

I have a try catch block that is checking if the input from Scanner is an int or not. But it instead just loops over and over again asking how many people to send.. then says Error: Not a number. Without actually prompting the user to enter in a different number.

        int peopleToSend = 0;

        //I attempted to do a try catch... but it isn't working how I planned it...
        while(peopleToSend < 1 || peopleToSend > peopleAlive()){
            try {
                System.out.print("\nHow many people would you like to send out? 1 - " + peopleAlive() + ": ");

                peopleToSend = scan.nextInt();
            } catch (Exception e) {
                System.out.println("Error: Not a number.");
            }
        }

Example of output when entering something other than an int.

How many people would you like to send out? 1 - 22: Error: Not a number.

How many people would you like to send out? 1 - 22: Error: Not a number.

How many people would you like to send out? 1 - 22: Error: Not a number.

How many people would you like to send out? 1 - 22: Error: Not a number.

*loops forever*

Add a scan.next(); statement after you catch the error:

        catch (Exception e) {
            System.out.println("Error: Not a number.");
            scan.next();
        }

只需在try块中编写while循环

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