【发布时间】:2014-01-18 15:00:54
【问题描述】:
我目前正在开发一款小游戏,但我遇到了无法自行解决的问题。我有一个方法可以读取输入并将其存储在变量中。对于任何错误的输入,将引发 IllegalArgumentException,您可以在其中再次尝试输入。但是,如果您再次做错了,它将继续进行下一个输入类型。但我希望它要求输入,直到输入有效。我的导师告诉我用我做的 try and catch 来做,但据说它只会做两次然后继续。
代码如下:
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);
}
}
}
}
}
我希望你能帮助我。谢谢!
【问题讨论】:
-
“但我希望它要求输入直到输入有效” 使用 do/while 结构。
-
@Sikorski 这个问题似乎是关于某人在做作业时遇到的问题。这不是典型的作业直接副本+问号问题之一。
-
我很好奇你为什么用
input.matches("[4-9]|10"),真的有必要吗?