我正在编写一个方法,并希望通过比较来启动该方法,以查看存储的静态字符串是否等于其他单词。这是在psuedocode中:

While (String1 is neither equal to "A" nor "B" nor "C" nor "D")
{
    Print (Please enter a correct option);
    Take input;
}


任何帮助都非常感谢。

最佳答案

对于您的情况,您有四个允许的输入,即"A", "B", "C", "D"。仅使用布尔运算符即可轻松实现;即循环条件是您的输入既不是"A"也不是"B"也不是"C"也不是"D"的情况。

Scanner input = new Scanner(System.in);

System.out.println("Enter a selection (NOR): ");
String string1 = input.next();

while (    !string1.equals("A")
        && !string1.equals("B")
        && !string1.equals("C")
        && !string1.equals("D")) {
    System.out.println("Enter again (NOR): ");
    string1 = input.next();
}
input.close();


但是,在任意但有限地有许多可接受的输入(例如具有匈牙利字母的所有字母)的情况下呢?该设置可能是最佳选择。

Scanner input = new Scanner(System.in);

// Either manually or use a method to add admissible values to the set
Set<String> admissible = new HashSet<String>();
admissible.add("A");
admissible.add("B");
admissible.add("C");
admissible.add("D");
// ... and so on. You can also use helper methods to generate the list of admissibles
// in case if it is in a file (such as a dictionary or list of words).

System.out.println("Enter a selection (Set): ");
String string1 = input.next();

// If input string1 is not found anywhere in the set
while (!admissible.contains(string1))  {
    System.out.println("Enter again (Set): ");
    string1 = input.next();
}
input.close();

07-28 02:10
查看更多