2016-11-06 17 views
2

私はクラスにあるすべてのオブジェクトをリストするコードに書き込もうとしています。 (動作していますが)プレーヤーが空であればオブジェクトがあるかどうかをチェックし、そうであれば画面にメッセージを出力するコードを取得したいと思います。しかし、私はそれを働かせることはできません。誰でも私を助けてくれますか?JAVAクラス配列

クラス

public void listAll() 
    { 
     for (Song a : songs) { 
     if(songs.isEmpty()) //cant get this to check if there are songs on the player. 
     { 
      System.out.print("There are no songs on the playlist"); 
     } 
     else{ 
      System.out.print(a); 
      } 
     } 
    } 

テスター

keyIn.nextLine(); //clear the buffer of the previous option 
        System.out.print("On player are"); 
        player.listAll(); 
        break; 
+1

'enhanced for loop'を使用しているときにその条件を確認する必要はありません。配列の次の要素がnullの場合、ループwilllは自動的に終了します。 –

+1

あなたはそれをデバッグしようとしましたか? – Mritunjay

+0

あなたはそれを動作させることができましたか? – ItamarG3

答えて

2

songsが空の場合、ループは入力されません。あなたは、ループの外を確認する必要があります。

public void listAll() { 
    if(songs.isEmpty()) { 
     System.out.println("There are no songs on the playlist"); 
    } else { 
     for (Song a : songs) { 
      System.out.println(a); 
     } 
    } 
} 
3

ループしたコードが全く起こらないようにするには、空のリストをループしようとしています。リストがループ外で空であるかどうかをチェックすると、望む結果が得られます。

public void listAll() { 
    if (songs.isEmpty()) // cant get this to check if there are songs on the 
    { 
     System.out.print("There are no songs on the playlist"); 
    } else { 
     for (Song a : songs) { 
      System.out.print(a); 
     } 
    } 

} 
2

listemptyであれば、実行はfor loop内で行っておりませんので、ごif条件文が取得することはありませんので、あなたがforループの外条件if(songs.isEmpty())をチェックする必要がありますまったく実行されません。

public void listAll() 
    { 
     //Check this first 
     if(songs.isEmpty()) 
     { 
      System.out.print("There are no songs on the playlist"); 
      return;//It is even more better to return from here itself 
     } 

     //NOW, use for loop 
     //if songs size is zero, execution does not go inside the for loop 
     for (Song a : songs) { 
      System.out.print(a); 
     } 
    } 

それであっても良く、あなたはその後の行を処理する必要がないことを示しているであろう、(上記のような)メソッドからの呼び出し元(すぐ)に戻ってreturnステートメントを使用することができる場合メソッド内のコード

+0

ありがとうございました。私が必要としている他の部分のためにこれを行うことができます:-) – americanheartbreak

関連する問題