虽然Loop While String不等于多个其他字符串(Java)

时间:2018-05-15 17:40:47

标签: java while-loop string-comparison

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

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

任何帮助都非常感谢。

4 个答案:

答案 0 :(得分:1)

正如Hemant在their comment中所述,使用Set来存储您想要检查的String内容是明智的:

Set<String> words = Set.of("Hello", "World!");

while (!words.contains(string1)) {
    ...
}

注意:{9}中引入了Set#ofstring1是您要检查的String

答案 1 :(得分:1)

// static set at top of the class
private static final Set<String> SET = new HashSet<>
                                (Arrays.asList("A", "B", "C", "D"));

void func() {

    String input = takeInput();
    while(!SET.contains(input)) {

        input = takeInput();
    }
}

答案 2 :(得分:1)

一种方法是构造一个简单的regular expression来匹配你的字符串:

String input = "";
while (!Pattern.matches("FirstString|SecondString|ThirdString", input)) {
    ...
}

正则表达式模式由您希望允许用垂直条|字符分隔的单词组成。

注意:使用while循环需要在进入循环之前将input设置为不匹配的String。您可以通过更改为do / while循环来改进此方法:

String input;
do {
    System.out.println("Please enter a correct option");
    input = takeInput();
} while (!Pattern.matches("FirstString|SecondString|ThirdString", input));

答案 3 :(得分:1)

在您的情况下,您有四个可接受的输入,即"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();