I need to get the list of songs

0

I wanted to print the list of songs stored in an array listaMusica :

   System.out.println(p.listarMusicas());

This is the method for saving the data:

  Musica v = new Musica(t, a, d, ano, g);
                         p.addMusica(v);

 public void addMusica(Musica música) {
    if (_musicas < _capacidade) {
        _listaMusica[_musicas] = música;
        _musicas++;
    }
}

And this is the listarMusicas() method:

   public String listarMusicas() {
    String res = "";
    for (int i = 0; i < _musicas; i++)
        res += i + ": " + _listaMusica[i].getTítulo();
    return res;
}

I'll make all the code available now at this link: link

I accept suggestions.

    
asked by anonymous 27.02.2017 / 05:34

1 answer

1

The code is extremely difficult to maintain, so it has some bugs that you should resolve (see below).

But to print the list, I suggest creating a toString () method in the Music class:

@Override
public String toString() {
    return "Musica [_titulo=" + _titulo + ", _autor=" + _autor
            + ", _duracao=" + _duracao + ", _ano=" + _ano + ", _genero="
            + _genero + "]";
}

This makes it easier to iterate over the array.

In the method listMusics () call this list and use a StringBuilder (which is more efficient) for string concatenation:

public String listarMusicas() {
    StringBuilder sb = new StringBuilder();
    for(Musica m: _listaMusica) {
        if(m!=null) {
            sb.append(m);
        }
    }
    return sb.toString();
}

Once you've done this, your code still has some issues that need fixing. I'll list them here:

  • Do not use an Array for the list of songs. Use List<Musica> . This is the right framework for your case, in which the list can grow and shrink. Another reason is not having to check if the element is null. The List has the exact size you need, and you can use forEach to iterate over it easily.
  • Do not use the _musicas variable to control the size of the Array (or List). The Array has the length property and the List has a size ().
  • When removing a song from the list, it does _musicas-- . Except if you remove it several times, the variable gets negative! This generates an ArrayOutOfBoundsException. One more reason not to control this from the outside.
  • Do not use variables with underscore (_) because it reduces readability.
  • Do not use variables with accents and nonstandard characters ( getTítulo , getDuração ). This will make it easier for you to open the code for other editors (or other people to use).

Good luck in your work.

    
10.03.2017 / 05:26