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

时间:2015-01-12 00:36:30

标签: java while-loop try-catch

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


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;

1 个答案:

答案 0 :(得分:1)

使用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;