My program recurses. Is there a way to fix this?

60 Views Asked by At

My problem is that whenever I try to catch the exception on "scannerGettingStarted", I always get the try catch exception from runProgram. I know that there is a recursion that is happening, but I still can't figure out what is it. Excuse my source code, it sucks.

private void scannerRecordBook(Scanner scanner){
        System.out.println();
        System.out.println("[ Method Success ]");
        System.out.println("School: " + schoolname);
        System.out.println("Grade Level: " + gradeLevel);
        System.out.println("Section: " + section);
    }
    
    
    private void scannerGettingStarted(Scanner scanner){
        System.out.println("\n[ Getting Started ]\n");
      
        while(loop2){
            try(scanner){
                System.out.print("School Name: ");
                schoolname = scanner.next();
                
                System.out.print("Grade Level: ");
                gradeLevel = scanner.nextInt();
            
                System.out.print("Section: ");
                section = scanner.next();

            
                if(schoolname == null || section == null){
                    System.out.println("""
                                   +-------------------------+
                                      Field cannot be empty
                                   +-------------------------+""");
                }
                else if(gradeLevel == 0){
                    System.out.println("""
                                   +-------------------------+
                                          Cannot be zero
                                   +-------------------------+""");
                }else{
                    loop2 = false;
                    scannerRecordBook(scanner);
                }
              
            }catch(Exception e){
                System.out.println();
                System.out.println("""
                                   +--------------------------------+
                                          An error has occurred!
                                             Input Mismatch
                                   +--------------------------------+""");
                System.out.println();
                scanner.nextLine();
            }
        }

    }
    
    private void runProgram(){
        input = new Scanner(System.in);
        
        System.out.println("""
                                    [ Student Gradebook ]
                                        "HS Edition"    
                                    
                                    [1] Start
                                    [2] Exit
                                   """);
        
        while(loop){
            try{
                
                System.out.print("Number: ");
                choiceOfUser = input.nextInt();
                
                switch(choiceOfUser){
                    case 1 :
                        loop = false;
                        scannerGettingStarted(input);
                        break;
                    
                    case 2 :
                        System.out.println("+---------------------------+");
                        System.out.println("-- Exit Program Successful --");
                        System.out.println("+---------------------------+");
                        input.close();
                        loop = false;
                        break;
                } 
            }catch(Exception error){
                System.out.println("""
                                   +--------------------------------+
                                          An error has occurred!
                                    The input is not on the choices.
                                   +--------------------------------+""");
                input.nextLine();
            }
        }
        input.close();
    }
    
    public Main(){
        runProgram();
    }
    
    public static void main(String[] args) {
        new Main();
    }

Current output with bug

[ Student Gradebook ]
     "HS Edition"

 [1] Start
 [2] Exit

Number: er
+--------------------------------+
       An error has occurred!
 The input is not on the choices.
+--------------------------------+
Number: 1

[ Getting Started ]

School Name: e
Grade Level: rtedd

+--------------------------------+
       An error has occurred!
          Input Mismatch
+--------------------------------+

+--------------------------------+
       An error has occurred!
 The input is not on the choices.
+--------------------------------+
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
    at java.base/java.util.Scanner.ensureOpen(Scanner.java:1158)
    at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1790)
    at java.base/java.util.Scanner.nextLine(Scanner.java:1658)
    at plate5.Main.runProgram(Main.java:177)
    at plate5.Main.<init>(Main.java:184)
    at plate5.Main.main(Main.java:188)

Expected output:

[ Student Gradebook ]
     "HS Edition"

 [1] Start
 [2] Exit

Number: er
+--------------------------------+
       An error has occurred!
 The input is not on the choices.
+--------------------------------+
Number: 1

[ Getting Started ]

School Name: e
Grade Level: rtedd

+--------------------------------+
       An error has occurred!
          Input Mismatch
+--------------------------------+

//Restarts back to the "School Name" scanner part

School Name: 
1

There are 1 best solutions below

3
Michiel Bugher On

The exception you are getting:

Exception in thread "main" java.lang.IllegalStateException: Scanner closed

This happens because you are using a try-with-resources try(scanner) { inside of the while loop. Try-with-resources will automatically close the resource that is within the parenthesis as soon as the try block exits.

try-with-resources is equivalent to:

Scanner input = new Scanner(System.in)
try {
 input.next() // use the scanner how you see fit
} finally {
 input.close(); // close the resource, it should not be used again.
}

This is problematic because you want to continue using the scanner. It would be better to invert the try statement and the while loop.

try(scanner) {
    while(loop) {
        scanner.next(); // do your thing
    }
}

Regarding what you are calling recursion (which is actually just multiple iterations) seems to be happening because you are not properly setting loop2 = false; on an exception. This block of code needs to do something like:

catch(Exception error){
    System.out.println("""
                               +--------------------------------+
                                      An error has occurred!
                                The input is not on the choices.
                               +--------------------------------+""");
    input.nextLine();
    loop2 = false;
}

if you don't want it to iterate again. This is the only thing that I see that could be causing the "recursion" that you mention. I'm guessing it is one of the two catch statements that are not being told to stop looping, so it does not stop and keeps iterating.

Side note: Working code that can be executed would make the question a whole lot easier to answer.