我正在尝试制作战舰。在这里,我想使用 Scanner
从控制台获取输入来确定拍摄地点。
while (x) {
while (counter) {
userInput = input.nextLine();
if (userInput.equals("cheat")) {
cheat = true;
}
uppercased = userInput.toUpperCase();
char[] c = uppercased.toCharArray();
if (uppercased.length() < 2) {
System.out.println("Error, invalid input9, try again");
break;
} else if (uppercased.equals("")) {
System.out.println("Error, invalid input1, try again");
break;
} else if (uppercased.length() > 2) {
System.out.println("Error, invalid input2, try again");
break;
} else if (c[0] < 65 || c[0] > 74) {
System.out.println("Error, invalid input3, try again");
break;
} else if (c[1] < 48 || c[1] > 57) {
System.out.println("Error, invalid input4, try again");
break;
} else {
code = uppercased;
target = map.get(uppercased);
targetPosition = target.getSymbol();
if (targetPosition != 46) {
System.out.println("You have shot here, try again");
break;
}
}
counter = false;
}
x = false;
code = uppercased;
}
问题是,当我给出错误的输入时,它不会询问新的输入,但它会执行我的程序的其余部分。
它应该过滤输入,所以它是这样的: “A1” 而不是用来确定拍摄地点。 如何过滤错误的输入并获取新的输入?
最佳答案
使用
break
会将您移出当前循环。使用
继续
,会将您移至当前循环的开头。
因此,在您的情况下,继续会更好,因为它会将您移至在内循环中读取输入的代码部分。
从这个循环中提取主体(如下所示)也很容易测试:)
更新:
while (x) {
while (!runCheck()) { Your main method is extracted from loop, making it more readable
}
x = false;
code = uppercased;
}
boolean runCheck(){
userInput = input.nextLine();
if ("cheat".equals(userInput)) { // prefer to compare String agains a constant in this way, it's immune to NPE, when by any chance userInput would be a null
cheat = true;
}
uppercased = userInput.toUpperCase();
char[] c = uppercased.toCharArray();
if (uppercased.length() < 2) {
System.out.println("Error, invalid input9, try again");
return true;
} else if ("".equals(uppercased)) {
...
} else {
code = uppercased;
if(!map.conainsKey(uppercased)){ // target can be null, or not existing in map
return true;
}
target = map.get(uppercased);
targetPosition = target.getSymbol();
if (targetPosition != 46) {
System.out.println("You have shot here, try again");
return true;
}
}
return false;
}
关于Java过滤器用户输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29606384/