2014-09-25 1 views
0

Вот мой Java код:Как выйти из нулевого значения в цикле в Java

public class DVD { 
    public static void main(String[] args) { 
     DVD newdvd1 = new DVD(); 

     newdvd1.setPlayit("The song is playing \n"); 
     newdvd1.setArtist("Eva Cassidy"); 
     newdvd1.setTitle("Songbird"); 
     newdvd1.setGenre("Blues"); 

     System.out.println(newdvd1.getPlayit()); 
     System.out.println(newdvd1); 

     DVD newdvd2 = new DVD(); 

     newdvd2.setPlayit("The next song is playing \n"); 
     newdvd2.setArtist("an unknown artist"); 
     newdvd2.setTitle("new song"); 

     System.out.println(newdvd2.getPlayit()); 
     System.out.println(newdvd2); 
    } 

    private String artist; 
    private String title; 
    private String genre; 
    private String playit; 

    public String getPlayit() { 
     return playit; 
    } 
    public void setPlayit(String playit) { 
     this.playit = playit; 
    } 
    public String getArtist() { 
     return artist; 
    } 
    public void setArtist(String artist) { 
     this.artist = artist; 
    } 
    public String getTitle() { 
     return title; 
    } 
    public void setTitle(String title) { 
     this.title = title; 
    } 
    public String getGenre() { 
     return genre; 
    } 
    public void setGenre(String genre) { 
     this.genre = genre; 
    } 

    public String toString() { 

     return ("The artist is called " + artist + 
      " who is a "+ genre + " singer" + 
      " and this song is called " + title + ".\n"); 
    } 
} 

, что он выдает это:

The song is playing 
The artist is called Eva Cassidy who is a Blues singer and this song is called Songbird. 
The next song is playing 
The artist is called an unknown artist who is a null singer and this song is called new song. 

То, что я спрашиваю, во второй песне , как я могу оставить «нулевой певец», поскольку я не хочу отображать второй жанр песен?

+2

'если (что-то == NULL) {doSomethingSpecial(); } ' – Thilo

ответ

0

Если вы хотите, чтобы решение было общим для затем изменить свой toString метод, как:

  public String toString() { 
      String returnString = "The artist is called " + artist ; 

      if(genre !=null && !"".equals(genre.trim())) { 
       returnString += " who is a "+ genre + " singer" +; 
      } 

      returnString += " and this song is called " + title + ".\n"; 
      return returnString; 
     } 

Вы можете добавить более нулевые чеки, если это необходимо для художника и название, а также.

0

Вы можете вставить нулевую проверку, чтобы пропустить эту часть. В любом случае вы должны использовать StringBuffer, иначе вы создадите много объектов String и сделаете GC сердитым. Каждый + создает новый объект String, поэтому с помощью StringBuffer вы создаете только одну строку в конце.

public String toString() 
{ 
    StringBuffer buffer = new StringBuffer("The artist is called "); 
    buffer.append(artist); 
    if(genre != null) 
    { 
     buffer.append(" who is a "); 
     buffer.append(genre); 
     buffer.append(" singer"); 
    } 
    buffer.append(" and this song is called "); 
    buffer.append(title); 
    buffer.append(".\n"); 
    return buffer.toString(); 
} 
2

Используйте ?: (тройной) оператор. См. Например, JLS specs.

    return ("The artist" + 
        (artist == null ? "" : " is called " + artist) + 
        (genre == null ? "" : " who is a "+ genre + " singer") + 
        (title == null ? "" : " and this song is called " + title) + 
        ".\n"); 

Если заданное свойство не является нулевым, вы печатаете соответствующий текст, иначе просто ничего не печатаете.

Вы можете также определить разумные значения по умолчанию, как:

    (artist == null ? " is unknown" : "is called " + artist) + 
+3

Я думаю, что стоит отметить, что оператор'?: 'Известен как« тернарный »оператор. – Mister

0

Вы должны переопределить toString() с помощью некоторого условия

public String toString() { 
if(genre!=null){ 
    return ("The artist is called " + artist + 
        " who is a "+ genre + " singer" + 
        " and this song is called " + title + ".\n"); 
    }else{ 
    return ("The artist is called " + artist + 
       " and this song is called " + title + ".\n");   
    } 

} 
+0

BOOM! мы в действии, большое спасибо – joewinfield91

+0

@ joewinfield91 приветствуются –

1

Вы можете попробовать это.

public String toString() { 
    StringBuilder builder = new StringBuilder(); 

    if (artist != null && !artist.isEmpty()) { 
     builder.append("The artist is called : " + artist); 
    } 

    if (genre != null && !genre.isEmpty()) { 
     builder.append(" who is a " + genre + " singer"); 
    } 
    if (title != null && !title.isEmpty()) { 
     builder.append(" and this song is called " + title + ".\n"); 
    } 

    return (builder.toString()); 
} 
0

Если его только о певице, вы можете сделать следующее:

public String toString() { 
    String temp = "The artist is called " + artist"; 
      if(singer != null){ //checks if the object "singer" is not null 
       temp+=" who is a " + genre + " singer"; 
      } 
    temp+="and this song is called "+ title + ".\n"; 
    return temp; 
} 
Смежные вопросы