在 java 中输入无效后重新提示用户(try and catch )

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

现在,它会在出现一个错误后无限循环。我怎样才能让它在捕获后返回到 try?布尔条件声明正确,没有编译错误或任何东西。 class 中的其余代码有点乱,因为我正在等待有关重试的答案。


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;

使用 hasNextDouble() 而不是使用 try/catch 异常,因为您没有明确捕获 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;