Search code examples
javarecursionstackcallstackcode-organization

How to avoid stack build up?


I'm trying to figure out how I can write this method to avoid the stack buildup from recursively calling the method in the exception?

Here is the wording of my instructions:

Read a number, use an exception handler to make sure it is an int number and then add to the ArrayList object, aryList.

Here is my attempt:

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

Any suggestions are greatly appreciated!


Solution

  • Simply use a do-while loop:

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

    Since initializing the Scanner keyboard each time is useless, it is put before the loop.