如何在 ChatBot 程序中实现第一个匹配关键字的条件?下面的代码是我正在使用的当前代码:
public static void firstMatchingKeyword1() {
String sex;
sex = JOptionPane.showInputDialog(null, "Are you a guy or woman?");
if (sex.contains("guy")) {
JOptionPane.showMessageDialog(null, "I am a guy too");
} else if (sex.contains("woman")) {
JOptionPane.showMessageDialog(null, "I am a woman too");
}
}
问题是,如果两个关键字都存在,我希望输出是第一个键入的关键字。 例如:如果用户输入“我是女人,但也是男人”。我希望输出只是消息“我也是女人”,而不是一个一个地检查所有 if 语句。
最佳答案
indexOf
是你的 friend 。
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
if (sex.indexOf("guy") > 0 && sex.contains("guy") && (sex.indexOf("guy")<sex.indexOf("woman") ||
sex.indexOf("woman") == -1)) {
{
JOptionPane.showMessageDialog(null, "I am a guy too");
} else if (sex.contains("woman")) {
JOptionPane.showMessageDialog(null, "I am a woman too");
}
关于java - 如何使 if/else 语句读取第一个匹配的关键字? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586453/