我当前的问题是检查当用户的输入不等于已定义数组中的任何字符串时如何创建条件以输出无效输入,并且在它是有效选项之前连续请求新输入。
代码:
public class GameMenu {
static String choice;
int userOption = 0;
public void printMainMenu() {
[...] /* Other code that prints out menu */
checkIfGuessComputerNumberIsChosen();
}
private void checkIfGuessComputerNumberIsChosen() {
Scanner menuInput = createNewScanner();
choice = menuInput.nextLine();
/* This code goes through the array of valid input */
for(; userOption < validGuessComputerNumberOptions().length; userOption++)
checkIfChoiceEqualsValidOption();
}
private void checkIfChoiceEqualsValidOption() {
if(choice.toLowerCase().equals(validGuessComputerNumberOptions()[userOption])) {
PlayGame();
}
}
private String[] validGuessComputerNumberOptions() {
String[] inputOptions = {"a", "b", "c", "d"}; // List of input options
return inputOptions;
}
}
我希望能够创建另一个方法,每当它与validGuessComputerNumberOptions()中找到的数组中的String不匹配时,就会要求用户输入;
我尝试了一些代码但是我继续得到一个数组索引超出范围错误。
不工作代码:
private void checkifGuessComputerNumberIsChosen() {
Scanner menuInput = createNewScanner(); // createNewScanner is a defined method in the code
choice = menuInput.nextLine();
for(; userOption < validGuessComputerNumberOptions.length; userOption++) {
checkIfChoiceEqualsValidOption();
while(!choice.toLowerCase().equals(validGuessComputerNumberOptions()[userOption])) /* If it is not equal to string */ {
choice = menuInput.nextLine();
}
}
具体来说,找出String是否不等于有效输入数组中的元素的最佳方法是什么,然后提示用户再次输入其输入。此外,赞赏有关代码的结构和功能的反馈。请注意,有效输入“a”,“b”[...]是示例有效输入,而不是实际输入。
答案 0 :(得分:1)
我建议您创建一个方法来执行此操作,然后在while loop
:
public boolean checkInput(String input)
{
String[] inputOptions = {"a", "b", "c", "d"};
for(String i : inputOptions)
{
if(input.equals(i))
{
return true;
}
}
return false;
}
while(!checkInput(choice))
{
choice = menuInput.nextLine();
}
//After this loop choice will be equal to a b c or d...
答案 1 :(得分:0)
您可能需要考虑切换到HashSet对象来存储候选字符串。
然后,您可以在〜常量时间内使用contains()方法来检查String是否匹配。
HashSet inputOptions = new HashSet<String>();
inputOptions.add("a")
inputOptions.add("b")
inputOptions.add("c")
if (inputOptions.contains("a")) {
//do something
}