如何在循环中进行try块?

时间:2015-11-17 13:46:11

标签: java loops try-catch

我刚刚在 Java 中了解了'try'语句,而我正在尝试做的是让这个输入循环直到用户的输入都是整数和正数。

到目前为止,这是我的代码:

int scanning () {

    Scanner scan = new Scanner(System.in);
    int input = 0;
    boolean loop = false;
        do {
            try {
                System.out.print("Amount: ");
                input = scan.nextInt();
                if (input < 0) {
                    System.out.println("Error. Invalid amount entered.");
                    loop = true;
                }
            } catch (Exception e) {
                System.out.println("Error: Invalid input");
                loop = true;
            }
        } while (loop);

    return input;
}

然而,当用户输入无效整数时,它会经历一个无限循环,一遍又一遍地打印错误消息。预期的结果是不断要求用户提供有效的输入。

4 个答案:

答案 0 :(得分:2)

此代码将帮助您处于无限循环中,并在输入为-ve整数时抛出异常。

java中的异常处理是处理运行时错误的强大机制之一,因此可以维护应用程序的正常流程。

大多数情况下,当我们在java中开发应用程序时,我们经常感到需要创建并抛出我们自己的异常。首先创建一个用户定义的异常AmountException。

      public class AmountException extends Exception {
            private static final long serialVersionUID = 1L;

            public AmountException() {
                // TODO Auto-generated constructor stub
                System.out.println("Error. Invalid amount entered");
            }
        }

现在将您的扫描()编辑为:

    int scanning () {
    Scanner scan = new Scanner(System.in);
    int input = 0;
    boolean loop = false;
    do {
        try {
            System.out.print("Amount: ");
            input = scan.nextInt();
            if (input < 0) {

                loop = true;
                throw new AmountException();

            } else {
                loop = false;
            }

        } catch (AmountException e) {

        }
    } while (loop);

    return input;
}

答案 1 :(得分:1)

在每次检查条件之前,在loop循环中重置do-while变量的值。

do {
  try {
    System.out.print("Amount: ");
    input = scan.nextInt();
    loop = false;             // Reset the variable here.
    if (input < 0) {
      System.out.println("Error. Invalid amount entered.");
      loop = true;
    }
  } catch (Exception e) {
    System.out.println("Error: Invalid input");
    scan.next();             // This is to consume the new line character from the previous wrong input.
    loop = true;
  }
} while (loop);

答案 2 :(得分:0)

从您的代码中,将循环更改为false,并在给出有效输入时,它将终止while循环

boolean loop = false;
    do {
        try {
            loop = false;
            System.out.print("Amount: ");
            input = scan.nextInt();
            if (input < 0) {
                System.out.println("Error. Invalid amount entered.");
                loop = true;
            }
        } catch (Exception e) {
            System.out.println("Error: Invalid input");
            loop = true;
        }

答案 3 :(得分:0)

else之后添加if阻止,否则,如果第一个输入无效,loop将始终保持true

if (input < 0) {
    System.out.println("Error. Invalid amount entered.");
    loop = true;
} else {
    loop = false;
}
相关问题