2016-09-28 6 views
-8

誰か助けてくれますか?Javaでのインデックスの支援 - プログラミング1

テキストの行は、これらの小文字のいずれかの単語が含まれ かどうかを出力し、単一if...else statement書く: "the""and""hello"

私はこれを試みたが、これまでその正しいとは思わないが。 String任意の 3の言葉が含まれている場合、私はString.contains(CharSequence)とのようなものを使用するかを決定するために

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

途中で文が途切れてしまった場合は、非常に難しいです... –

+0

どこから行くのかわかりませんでした。 – YawdMan

+0

'と'が 'バンド'という単語を見つけるのはいいですか?はいの場合、あなたは正しい道を歩いています。いいえの場合は、 'split()'や正規表現を使う必要があります。 – Andreas

答えて

2

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