[英]catching exceptions recursively in Java
我正在做一个小游戏,我遇到了一个我无法解决的问题。 我有一个读取输入并将其存储在变量中的方法。 对于任何错误的输入,将抛出IllegalArgumentException,您可以再次尝试输入。 但是,如果你再次做错了,它将进入下一个输入类型。 但我希望它在输入有效之前询问输入。 我的导师告诉我这样做尝试并抓住我做了但是如上所述它只会做两次然后继续。
这是代码:
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);
}
}
}
}
}
我希望你能帮助我。 谢谢!
第一步是要意识到你正在重复你的“读取代码长度”。 这通常意味着两件事:1)您应该将代码提取到方法中并多次调用该方法,或者2)您应该使用循环并在循环中编写代码。 (或两者)
循环的建议应响铃,因为只有那个(或递归...)允许你按照你想要的那样重复操作非固定次数。 在伪代码中:
repeat
readNumber
until number is valid
如您所见,条件位于循环的底部。 在Java中,你可以使用do {...} while(...);
- 请注意,您必须从伪代码中撤消条件,因为它是暂时的, while
不是until
。
在旁注中,当您自己抛出异常时,您可以跳过抛出,而是将codelength
为您认为无效的值,例如-1
。 无论如何你都需要它,因为你必须将异常作为readNumber
部分的一部分来捕获,它仍然在你的循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.