I need to get the list of songs

Asked

Viewed 115 times

0

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

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

This is the method for storing 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 method listarMusicas():

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

I will make all the code now available at this link: http://pastebin.com/4rY6dtab

I accept suggestions.

  • 2

    I don’t understand. What do you want to do? The list methodMusicas() already answers your question. Maybe adding an n after getTitulo() is better to read, but I don’t know if that’s what you want.

  • Why don’t you use List<Musica>?

  • When I do it it doesn’t really show the list of songs

  • Some can help me?

1 answer

1


The code is extremely difficult to maintain, and so it has some bugs that you should solve (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 listMusic() method 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 done, your code still has some issues that need to be fixed. I’ll list them here:

  • Do not use an Array for the playlist. Use an List<Musica>. This is the correct structure for your case, in which the list can grow and decrease. Another reason is not need 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 variable _musicas 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--. Only if you remove several times, the variable turns negative! This generates an Arrayoutofboundsexception. Another reason not to control this from the outside.
  • Do not use variables with underscore (_) as it decreases readability.
  • Do not use non-standard accents and characters variables (getTítulo, getDuração). This will make it easier for you when opening the code by other editors (or other people using it).

Good luck in your work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.