如何在循环中创建 try 块?

How to make a try block within a loop?

我刚刚了解到 'try' 中的语句 Java,以及我正在尝试的内容要做的是让这个输入循环,直到用户的输入既是整数又是正数。

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

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;
}

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

根据您的代码,将循环更改为 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;
        }

if之后添加一个else块,否则,如果第一个输入无效,loop将一直保持true

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

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

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);

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

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

大多数时候,当我们在 java 中开发应用程序时,我们常常觉得需要创建并抛出我们自己的 exceptions.So 首先创建一个用户定义的异常 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");
            }
        }

现在将您的 scanning() 编辑为:

    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;
}