测试X = A,B或C.

时间:2014-03-03 11:02:09

标签: java testing

我确信这有一个答案,但我似乎无法找到它,我一直在寻找几个小时。

标题几乎总结了,如何测试X = A,B或C

Qhey =“嘿”;

Qhi =“hi”;

Qhello =“你好”;

我得到了这段代码:

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);                                

        }
    }

4 个答案:

答案 0 :(得分:1)

使用or运算符。 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

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

答案 1 :(得分:1)

如果您可能只有三个字符串可以匹配,那么您应该使用Set

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

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

这种方法的另一个优点是时间复杂度为O(1) - 仅需要稍长的时间来检查1,000,000个字符串而不是3个。

答案 2 :(得分:0)

试试:

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

||表示“或”。

答案 3 :(得分:0)

替换

  

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

    String text = InputField.getText();
    if(text.contains(Qhey) ||  text.contains(Qhi) ||  text.contains(Qhello))