在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 楼答案
第一步是意识到你在重复你的“阅读代码长度”。这通常意味着两件事:1)应该将代码提取到方法中并多次调用该方法,或者2)应该使用循环并在循环中编写代码。(或两者兼而有之)
循环的建议应该引起注意,因为只有循环(或递归…)允许您按照自己的意愿,以不固定的次数重复该操作。在伪代码中:
如您所见,条件位于循环的底部。在Java中,可以使用
do {...} while(...);
——注意,必须从伪代码中反转条件,因为它是while
,而不是until
另一方面,当您自己抛出异常时,您可以跳过抛出,而将
codelength
保留在您认为无效的值,例如-1
。无论如何,您都需要它,因为您必须捕获异常作为readNumber
部分的一部分,它仍然在您的循环中