要確定String
包含任何三個詞,我會用String.contains(CharSequence)
之類的東西
if (line.contains("the") || line.contains("and") || line.contains("hello")) {
System.out.println(line + " contains the, and or hello");
} else {
System.out.println(line + " does not contain the, and or hello");
}
但如果加上「你好」喜歡你目前的做法應該工作(和它的其他後{
,不(
)。
if (line.indexOf("the") >= 0 || line.indexOf("and") >= 0
|| line.indexOf("hello") >= 0) {
System.out.println(line + " contains the, and or hello");
} else {
System.out.println(line + " does not contain the, and or hello");
}
但是,我注意到你在你的例子中省略了大括號。你可以這樣做,但是你的陳述只適用於下一行。
if (line.indexOf("the") >= 0 || line.indexOf("and") >= 0
|| line.indexOf("hello") >= 0)
System.out.println(line + " contains the, and or hello");
else
System.out.println(line + " does not contain the, and or hello");
而且你可以混合使用括號像
if (line.indexOf("the") >= 0 || line.indexOf("and") >= 0
|| line.indexOf("hello") >= 0) {
System.out.println(line + " contains the, and or hello");
} else
System.out.println(line + " does not contain the, and or hello");
或者
if (line.indexOf("the") >= 0 || line.indexOf("and") >= 0
|| line.indexOf("hello") >= 0)
System.out.println(line + " contains the, and or hello");
else {
System.out.println(line + " does not contain the, and or hello");
}
但我更喜歡到總是使用括號。
很難說,如果這是正確的,因爲你停止中期聲明...... –
不知道從那裏去哪裏..我在正確的道路,雖然? – YawdMan
'和'可以找到單詞'band'嗎?如果是,那麼你在正確的道路上。如果不是,那麼你需要使用'split()'或一個正則表達式。 – Andreas