我确定对此有答案,但我似乎找不到,我已经搜索了几个小时。
标题几乎概括了它,我如何测试 X = A、B 或 C
Qhey = "嘿";
Qhi = "你好";
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);
}
}
最佳答案
如果要匹配的字符串可能不止三个,那么您应该使用 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 个字符串稍微长一些。
关于java - 测试 X = A、B 或 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22145014/