我试图弄清楚如何编写此方法,以避免在异常中递归调用该方法而导致堆栈堆积?

这是我的指示文字:


  读取一个数字,使用异常处理程序确保它是一个整数,然后将其添加到ArrayList对象aryList中。


这是我的尝试:

public void createOriginalAryList() {

      Scanner keyboard = new Scanner(System.in);

      System.out.println("Enter a number: ");

      try {

         int number = keyboard.nextInt();
         aryList.add(number);

         while(keyboard.hasNextInt()) {

            System.out.println("Enter a number: ");
            number = keyboard.nextInt();
            aryList.add(number);

         }

      } catch(InputMismatchException ime) {
         System.out.println("Invalid number submitted! Try again.");
         createOriginalAryList();
      }

      System.out.println(aryList);
   }


任何建议,不胜感激!

最佳答案

只需使用do-while循环:

Scanner keyboard = new Scanner(System.in);

boolean redo = false;
do {
    System.out.println("Enter a number: ");
    redo = false;
    try {
       int number = keyboard.nextInt();
       aryList.add(number);

       while(keyboard.hasNextInt()) {

          System.out.println("Enter a number: ");
          number = keyboard.nextInt();
          aryList.add(number);

       }

    } catch(InputMismatchException ime) {
       redo = true;
       System.out.println("Invalid number submitted! Try again.");
    }
}
while(redo);
System.out.println(aryList);


由于每次初始化Scanner keyboard都是无用的,因此将其放在循环之前。

关于java - 如何避免堆栈堆积?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22367816/

10-10 06:36