JAVA:使用 if-cond 调用相同的方法,而不执行更多(旧)代码
JAVA: Call same method with if-cond, without execution of further(old) code
我想我要做的是回调。
我有一个提示询问用户是否要换狼。
如果用户按下 "YES",则用户可以输入两位数。
如果这些与我的模式不匹配,我想再次调用该方法。
到目前为止,还不错。
但是我输入错误的pattern后又出现提示,然后输入正确的pattern后还是报错,这次是把之前的错误pattern传给了parse的try catch。
这点我不明白。
在失败的模式下,我再次调用了该方法,所以代码应该退出我的方法,而不是存储任何值并再次重新输入,对吗?
那么为什么它试图从之前的方法调用中解析错误的模式。
它应该尝试解析新输入的值(正确的模式)但坚持使用旧值。
非常感谢你们的帮助。
提前致谢。
public class Wolf{
Scanner scannerInstance;
int[] position;
public Wolf (){
scannerInstance = new Scanner(System.in);
position = {2,2};
}
public static void main(String[] args){
Wolf w = new Wolf();
w.changeWolf();
}
public Wolf changeWolf(Wolf w) {
out("Change the wolf? (Yes/No)");
switch (scannerInstance.nextLine()) {
case "NO":
break;
case "YES":
changeCrds(w);
changeWolf(w);
break;
default:
out("Invalid.");
changeWorld(w);
break;
}
return w;
}
public void changeCrds(Wolf w){
String input = getNext();
String[] inputField;
if (!input.matches("\d+,\d+")) {
out("Invalid. REGEX error");
changeCrds(w);
}
inputF = input.split(",");
int w = 0; int t = 0;
try {
w = Integer.parseInt(inputF[0]);
t = Integer.parseInt(inputF[1]);
} catch (Exception e) {
out("Invalid. PARSe error");
changeCrds(w);
}
int[0] = w;
int[1] = t;
}
}
您的方法应该在错误检测后退出。
if (!input.matches("\d+,\d+")) {
out("Invalid. REGEX error");
changeCrds(w);
return; // add this
}
我想我要做的是回调。
我有一个提示询问用户是否要换狼。 如果用户按下 "YES",则用户可以输入两位数。 如果这些与我的模式不匹配,我想再次调用该方法。 到目前为止,还不错。
但是我输入错误的pattern后又出现提示,然后输入正确的pattern后还是报错,这次是把之前的错误pattern传给了parse的try catch。
这点我不明白。 在失败的模式下,我再次调用了该方法,所以代码应该退出我的方法,而不是存储任何值并再次重新输入,对吗? 那么为什么它试图从之前的方法调用中解析错误的模式。
它应该尝试解析新输入的值(正确的模式)但坚持使用旧值。
非常感谢你们的帮助。 提前致谢。
public class Wolf{
Scanner scannerInstance;
int[] position;
public Wolf (){
scannerInstance = new Scanner(System.in);
position = {2,2};
}
public static void main(String[] args){
Wolf w = new Wolf();
w.changeWolf();
}
public Wolf changeWolf(Wolf w) {
out("Change the wolf? (Yes/No)");
switch (scannerInstance.nextLine()) {
case "NO":
break;
case "YES":
changeCrds(w);
changeWolf(w);
break;
default:
out("Invalid.");
changeWorld(w);
break;
}
return w;
}
public void changeCrds(Wolf w){
String input = getNext();
String[] inputField;
if (!input.matches("\d+,\d+")) {
out("Invalid. REGEX error");
changeCrds(w);
}
inputF = input.split(",");
int w = 0; int t = 0;
try {
w = Integer.parseInt(inputF[0]);
t = Integer.parseInt(inputF[1]);
} catch (Exception e) {
out("Invalid. PARSe error");
changeCrds(w);
}
int[0] = w;
int[1] = t;
}
}
您的方法应该在错误检测后退出。
if (!input.matches("\d+,\d+")) {
out("Invalid. REGEX error");
changeCrds(w);
return; // add this
}