简体   繁体   中英

re-prompt user after invalid input in java (try and catch )

Right now, it loops infinitely on the catch after one error. How can I make it go back to the try after a catch? boolean condition is declared properly, no compilation errors or anything. The rest of the code in the class is kind of a mess as I'm waiting for an answer about the re-trying.


double base = 0;
double height = 0;
double area = 0;
boolean again = true;
while (again) {
    try {
        System.out.print("Enter the length of base of triangle in cm : ");
        base = input.nextDouble();
        again = false;
    } catch (Exception ex) {
        System.out.println("Invalid input");
        input.next();
    }

    try {
        System.out.print("Enter the length of height of triangle in cm : ");
        height = input.nextDouble();
    } catch (Exception ex) {
        System.out.println("Invalid Input");
        String next = input.next();
    }
    area = (base * height) / 2;

use hasNextDouble() instead of using try/catch exception since you are not explicitly catching InputMismatchException

   while (again) {

             // if the next is a double, print the value
             if (input.hasNextDouble()) {
                base = input.nextDouble();
                System.out.println("You entered base: " + base);
                again = false;
             } else {
                // if a double is not found, print "Not valid"
                System.out.println("Not valid :" + input.next());
                again = true;
             }


      }
    again = true;
    while (again) {

             // if the next is a double, print the value
             if (input.hasNextDouble()) {
                height = input.nextDouble();
                System.out.println("You entered height: " + height);
                again = false;
             } else {
                // if a double is not found, print "Not valid"
                System.out.println("Not valid :" + input.next());
                again = true;
             }


      }
      area = (base * height) / 2;

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