2016-09-28 60 views
-8

有人可以幫我這個嗎?在Java幫助索引 - 編程1

寫入單個if...else statement輸出文本行是否包含 任何一個小寫的話: "the""and""hello"

我試過,但不認爲它正確爲止:

if(line.indexOf("the") >= 0 || line.indexOf("and") >= 0) 
    System.out.print("Contains one of the words"); 
     else (
+0

很難說,如果這是正確的,因爲你停止中期聲明...... –

+0

不知道從那裏去哪裏..我在正確的道路,雖然? – YawdMan

+0

'和'可以找到單詞'band'嗎?如果是,那麼你在正確的道路上。如果不是,那麼你需要使用'split()'或一個正則表達式。 – Andreas

回答

2

要確定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");   
} 

但我更喜歡總是使用括號。

+0

謝謝你真的很感激它! – YawdMan