YYZcode
YYZcode

Reputation: 3

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;

Upvotes: 0

Views: 2606

Answers (1)

display name
display name

Reputation: 4185

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;

Upvotes: 1

Related Questions