【发布时间】:2020-12-28 16:32:46
【问题描述】:
当下面的这个方法checkUserInput()只被调用一次(当用户的第一个条目是从1到3的数字时)它工作正常。
但是,当多次调用该方法时,它会按预期打印出正确的错误消息并重新运行“Enter”。然而,当用户此时键入一个从 1 到 3 的数字时,程序的运行方式有所不同:它不将数字识别为数字,或者它不通过减一来转换数字,或者它到达末尾并且再次运行。
可能是什么原因?
static List checkUserInput() {
System.out.print("Enter: ");
int g = 0, h = 0;
boolean numeric = true;
boolean numera = true;
Scanner scanner = new Scanner(System.in);
int xAxis = 0, yAxis = 0, a = 0, r = 0;
String m = scanner.next();
try {
yAxis = Integer.parseInt(m);
} catch (NumberFormatException e) {
numeric = false; //
}
if (!numeric) {
System.out.println(" numbers only!"); //exclude letters
checkUserInput();
}
String n = scanner.next();
try {
xAxis = Integer.parseInt(n);
} catch (NumberFormatException e) {
numera = false; //
}
if (!numera) {
System.out.println(" numbers only!"); //exclude letters
checkUserInput();
} else if (xAxis < 1 || xAxis > 3 || yAxis < 1 || yAxis > 3) {
System.out.println("1 to 3 only!");
checkUserInput();
} else {
//inputs that pass all tests can proceed
//assign array indices to respective coordinates
g = yAxis - 1;
h = xAxis - 1;
}
cords = new ArrayList<Integer>();
cords.add(g);
cords.add(h);
return cords;
}
【问题讨论】:
-
我强烈建议你学习如何调试你的程序,它将帮助你理解它是如何工作的。