Java 如果X=A、B或C,则进行测试

Java 如果X=A、B或C,则进行测试,java,testing,Java,Testing,我肯定有答案,但我似乎找不到,我已经找了好几个小时了 标题大致概括了这一点,如何测试X=A、B或C Qhey=“嘿” Qhi=“hi” Qhello=“hello” 我得到了一段代码: if(InputField.getText().contains(Qhey)) { try { textArea.getDocument().insertString(0,Qhello +", todays date is "+day+"/"+month+"/"+y

我肯定有答案,但我似乎找不到,我已经找了好几个小时了

标题大致概括了这一点,如何测试X=A、B或C

Qhey=“嘿”

Qhi=“hi”

Qhello=“hello”

我得到了一段代码:

if(InputField.getText().contains(Qhey))
    {
        try {
            textArea.getDocument().insertString(0,Qhello +", todays date is "+day+"/"+month+"/"+year + "\n", null);

        }catch (BadLocationException ex) {
                Logger.getLogger(ClassStart.class.getName()).log(Level.SEVERE, null, ex);                                

        }
    } 
我想把它做成这样:

if(InputField.getText().contains(Qhey, Qhi, Qhello))
    {
        try {
            textArea.getDocument().insertString(0,Qhello +", todays date is       "+day+"/"+month+"/"+year + "\n", null);

        }catch (BadLocationException ex) {
                Logger.getLogger(ClassStart.class.getName()).log(Level.SEVERE, null, ex);                                

        }
    }

使用
运算符

试试看:

if(InputField.getText().contains(Qhey) || InputField.getText().contains(Qhi) || InputField.getText().contains(Qhello))
|
表示“或”

替换

if(InputField.getText().contains(Qhey,Qhi,Qhello))


如果要匹配的字符串可能不止三个,那么应该使用
集合

static final Set<String> matches = Collections.unmodifiableSet(
     new HashSet(Arrays.asList("A", "B", "C")));

boolean isMatch(String s) { return matches.contains(s); }
static final Set matches=Collections.unmodifiableSet(
新的HashSet(Arrays.asList(“A”、“B”、“C”));
布尔isMatch(字符串s){返回匹配项。包含(s);}
这种方法的另一个优点是时间复杂度为O(1)——检查1000000个字符串只需比检查3个字符串稍微长一点

    String text = InputField.getText();
    if(text.contains(Qhey) ||  text.contains(Qhi) ||  text.contains(Qhello))
static final Set<String> matches = Collections.unmodifiableSet(
     new HashSet(Arrays.asList("A", "B", "C")));

boolean isMatch(String s) { return matches.contains(s); }