如何避免堆栈累积?

时间:2014-03-13 02:17:59

标签: java recursion stack callstack code-organization

我正在试图找出如何编写此方法以避免在异常中递归调用该方法的堆栈构建?

以下是我的指示措辞:

  

读取一个数字,使用异常处理程序确保它是一个int数,然后添加到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);
   }

非常感谢任何建议!

1 个答案:

答案 0 :(得分:2)

只需使用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都没用,因此将它放在循环之前。