2014-03-03 71 views
0

我确定有一个答案,但我似乎无法找到它,我一直在寻找几个小时。测试X = A,B或C

标题几乎总结起来,如何测试,如果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);         

     } 
    } 

回答

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的检查时间稍长。

0

试一下:

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

||手段 “或”。

0

更换

如果(InputField.getText()。含有(Qhey,Qhi,Qhello))

String text = InputField.getText(); 
    if(text.contains(Qhey) || text.contains(Qhi) || text.contains(Qhello)) 
相关问题