我正在努力建造战舰。在这里,我希望通过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;
}
问题是,当我输错了输入时,它不会询问新的输入,但它会执行我的其余程序。
它应该过滤输入,所以它是这样的: &#34; A1&#34; 比它用来阻止射击的地方。 如何过滤错误的输入并获得新的输入?
答案 0 :(得分:0)
使用break
会将您移到当前循环之外。
使用continue
会将您带到当前循环的开头。
所以在你的情况下,继续会更好,因为它会将你移动到你在内循环中读取输入的代码的一部分。
从这个循环中提取主体(如下所示)也很容易测试:)
更新
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;
}