简体   繁体   English

在Java中递归地捕获异常

[英]catching exceptions recursively in Java

I´m currently working on a little game and I´ve ran into a problem I cannot fix myself. 我正在做一个小游戏,我遇到了一个我无法解决的问题。 I´ve got a method which reads the input and stores it in variables. 我有一个读取输入并将其存储在变量中的方法。 For any wrong input will an IllegalArgumentException be thrown where you can try the input once again. 对于任何错误的输入,将抛出IllegalArgumentException,您可以再次尝试输入。 But if you´re doing it wrong once again, it will just proceed to the next input type. 但是,如果你再次做错了,它将进入下一个输入类型。 But I want it to ask for the input till the input is valid. 但我希望它在输入有效之前询问输入。 My tutor told me to do it with try and catch which I did but as said it will only do it twice and then proceed. 我的导师告诉我这样做尝试并抓住我做了但是如上所述它只会做两次然后继续。

Here´s the code: 这是代码:

 public void readSettings(){
    Scanner userinput = new Scanner(System.in);
    System.out.println("Wie lange soll der Code sein? (4-10):");
    String input = userinput.nextLine();
    //Eingabe der Länge des zu lösenden Codes. Bei einer Eingabe außerhab des Wertebereichs wird dies gemeldet und neu gefragt.
    try{
        if (input.matches("[4-9]|10")) {
            this.codelength = Integer.parseInt(input);  
        }
        else {
            throw new IllegalArgumentException();
        }
    }

    catch (IllegalArgumentException e) {
        System.out.println("Eingabe außerhalb des Wertebreichs!"); 
        //readSettings();
        System.out.println("Wie lange soll der Code sein? (4-10):");
        input = userinput.nextLine();
        if (input.matches("[4-9]|10")) {
            this.codelength = Integer.parseInt(input);  
        }
        else {
            throw new IllegalArgumentException(e);
        }
    } finally {

        System.out.println("Welche Ziffern sind erlaubt? 0- (1-9):");
        input = userinput.nextLine();
        //Hier wird die valuerange(Also die Maximale Zahl in der Reihe) abgefragt. 
        //Auch hier wird eine falche Eingabe abgefangen und der Input neu gestartet. (Leider nicht sehr elegant und benutzerfreundlich.
        try {
            if (input.matches("[1-9]")) {
                this.valuerange = Integer.parseInt(input);  
            }
            else {
                throw new IllegalArgumentException();
            }
        }
        catch (IllegalArgumentException f) {
            System.out.println("Eingabe außerhalb des Wertebreichs!"); 
            //readSettings();
            System.out.println("Welche Ziffern sind erlaubt? 0- (1-9):");
            input = userinput.nextLine();
            if (input.matches("[1-9]")) {
                this.valuerange = Integer.parseInt(input);  
            }
            else {
                throw new IllegalArgumentException(f);
            }
        } finally {

            //Falls der Modus nicht Cpmouter gegen Computer ist, wird ein Spielername mit abgefragt.
            try {
                if(!cpumode) {
                    System.out.println("Spielername:");
                    this.spielername = userinput.nextLine();
                    //Falls kein input bein Namen vorhanden, wird ein Fehler ausgegeben.
                    if (spielername.length()==0) {
                        throw new IllegalArgumentException("Fehler, kein Spielername eingegeben!" );  

                    }     
                }
            } catch (IllegalArgumentException e) {
                System.out.println("Spielername:");
                this.spielername = userinput.nextLine();
                if (spielername.length()==0) {
                    //throw new IllegalArgumentException("Fehler, kein Spielername eingegeben!" );  
                    throw new IllegalArgumentException(e);
                }     

            }   
        }
    }
}       

I hope you can help me. 我希望你能帮助我。 Thank you! 谢谢!

The first step is to realize that you're repeating your "read code length" all over. 第一步是要意识到你正在重复你的“读取代码长度”。 This could generally mean two things: 1) you should extract the code into a method and call that method multiple times, or 2) you should use a loop and write the code in the loop. 这通常意味着两件事:1)您应该将代码提取到方法中并多次调用该方法,或者2)您应该使用循环并在循环中编写代码。 (or both) (或两者)

the suggestion of a loop should ring a bell, because only that (or recursion...) allows you to repeat the operation a non-fixed number of times, as you want it. 循环的建议应响铃,因为只有那个(或递归...)允许你按照你想要的那样重复操作非固定次数。 In pseudocode: 在伪代码中:

repeat
    readNumber
until number is valid

as you see, the condition is at the bottom of the loop. 如您所见,条件位于循环的底部。 In Java, you'd use do {...} while(...); 在Java中,你可以使用do {...} while(...); - note that you have to reverse the condition from the pseudocode, because it's while , not until . - 请注意,您必须从伪代码中撤消条件,因为它是暂时的, while不是until

On a side note, as you throw the exception yourself, you could just skip the throwing and instead leave your codelength at a value you recognize as invalid, eg -1 . 在旁注中,当您自己抛出异常时,您可以跳过抛出,而是将codelength为您认为无效的值,例如-1 You'll need that anyway, as you have to catch the Exception as part of the readNumber part, which is still inside your loop. 无论如何你都需要它,因为你必须将异常作为readNumber部分的一部分来捕获,它仍然在你的循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM