简体   繁体   中英

Using a Try / Catch in a while loop

I'm asking my user to input via regex format "ABC-1234" otherwise an IllegalArgumentException is thrown. I would like to keep asking for the correct input (I'm thinking while or do while with a boolean variable set to false while input is incorrect...) how would I do that with a try / catch?

Here's what I have thus far. Thanks!

try {
            Scanner in = new Scanner (System.in);

            System.out.println("Please enter id: ");
            String id = in.nextLine();

            Inventory i1 = new Inventory (id, "sally", 14, 2, 2);
            System.out.println(i1);

        } catch (Exception ex) {

             System.out.println(ex.getMessage());

        }

Obviously, you need some kind of loop and you need some mechanism to break out of the loop on success. Supposing IllegalArgumentException is thrown from Inventory constructor, your solution can simply be:

while (true) {
    try {
        // ...
        Inventory i1 = new Inventory(id, "sally", 12, 2, 2);
        System.out.println(i1);
        break; // or return i1 if you enclose this snippet in a function
    } catch (Exception ex) {
        // ...
    }
} 

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