我的程序是递归的。有办法解决这个问题吗?

问题描述 投票:0回答:1

我的问题是,每当我尝试捕获“scannerGettingStarted”上的异常时,我总是从 runProgram 中获取 try catch 异常。我知道正在发生递归,但我仍然不知道它是什么。请原谅我的源代码,它很糟糕。

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

当前输出有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)

预期输出:

[ 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: 
java java.util.scanner
1个回答
0
投票

您遇到的异常:

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

发生这种情况是因为您在 while 循环内使用了 try-with-resources

try(scanner) {
。 Try-with-resources 会在 try 块退出时自动关闭括号内的资源。

try-with-resources 相当于:

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

这是有问题的,因为您想继续使用扫描仪。 最好将 try 语句和 while 循环颠倒过来。

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

关于您所调用的

recursion
(实际上只是多次迭代)似乎正在发生,因为您没有在异常上正确设置
loop2 = false;
。 该代码块需要执行以下操作:

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

如果你不想让它再次迭代。这是我看到的唯一可能导致您提到的“递归”的事情。我猜这是两个没有被告知停止循环的 catch 语句之一,因此它不会停止并继续迭代。

旁注:可以执行的工作代码将使问题更容易回答。

© www.soinside.com 2019 - 2024. All rights reserved.