3

foreach ループを使用して arraylist を実行し、名前を文字列と比較しています。しかし、名前を文字列と比較すると、常に出力される理由がわかりません。

for (Picture item : collection) {


                System.out.println("This is the label " + item.getName());

                if (item.getName().equals("This shouldn't work")); {

                System.out.println("Why is this working");

                }
            }
        }

出力

getting the name test A 
This is the label A
getting the name test A
Why is this working
getting the name test B
This is the label B
getting the name test B
Why is this working
4

3 に答える 3

4

セミコロンは、ブロックの構成要素であるステートメントの終わりを示します。入力することで

if (condition);
{ 
  System.out.println("Why is this working");
}

あなたが示している

if (condition)
  // empty statement
;
{ // unconditional opening of a block scope
  System.out.println("Why is this working");
}

したがって、ifステートメントが true と評価された場合は何も起こらず、false と評価された場合、空のステートメントはスキップされます。これは、何も起こらないことと同じです。

そのセミコロンを削除した場合、次の「ステートメント」はブロックスコープの開始になります。

if (condition) { 
  // conditional opening of a block scope
  System.out.println("Why is this working");
}

条件が false の場合、出力として「Why is this working」をスキップして、期待される動作を確認できたはずです。

于 2013-10-15T15:13:33.417 に答える
1

if (item.getName().equals("This shouldn't work"));// ここにセミコロンがあります

あなたのコードは以下のようになるはずです

if (item.getName().equals("This shouldn't work")){

 }
于 2013-10-15T15:12:39.547 に答える
0

変化する

if (item.getName().equals("This shouldn't work")); {

if (item.getName().equals("This shouldn't work")) {

セミコロンを置くと、ifステートメントが終了します

于 2013-10-15T15:13:23.680 に答える