"toString()" returning Null when it should not

Asked

Viewed 514 times

3

I have the class Aluno.

public class Aluno {

    private String nome;

    @Override
    public  String toString() {
        return this.nome;
    }
    //metodos getters e setters

}

Class Vetor

public class Vetor {

    private Aluno[] alunos = new Aluno[5];

    public void Adiciona(Aluno aluno) {
        for(int i = 0; i < alunos.length; i++) {
            if(alunos[i] == null) { //encontrou uma posicao vazia
               alunos[i] = aluno;
               break;
            }
        }


    public int tamanho() {

        return this.alunos.length;
    }

    @Override
    public String toString() {

        if(this.alunos.length == 0) {
            return "[]";
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[");

        for(int i = 0; i < this.alunos.length - 1; i++) {
            builder.append(this.alunos[i]);
            builder.append(", ");
        }

        builder.append(this.alunos[this.alunos.length - 1]);
        builder.append("]");

        return builder.toString();


        }
    }

When I have it printed here, it returns all the elements of the vectors:

public class Teste {

    public static void main(String[] args) {

        Aluno a1 = new Aluno();
        Aluno a2 = new Aluno();

        a1.setNome("Joao");
        a2.setNome("Maria");

        Vetor lista = new Vetor();
        lista.Adiciona(a1);
        lista.Adiciona(a2);

        System.out.println(lista);
    }
}

The result that returns is this:

[Joao, Maria, null, null, null, null]

  • It’s not wrong. You started a vector with 5 "spaces" and only filled two, so the return of the other spaces will be null.

  • How do I not print? I tried != null, but it’s not right

  • If you tried, you could have asked the question to tell us what’s wrong.

1 answer

3


The toString() should not be used for this. If the workbook encourages this use, I’m sorry. But come on.

You need to have an instruction to stop listing the rest of the array when you find a null or at least filter it:

builder.append("[");
if (this.alunos[0] != null) builder.append(this.alunos[0]);
for (int i = 1; i < this.alunos.length; i++) {
    if (this.alunos[i] != null) {
        builder.append(", ");
        builder.append(this.alunos[i]);
    }
}
builder.append("]");
return builder.toString();

If when you find a null, it’s by making sure that all the following ones are also null, you can improve:

builder.append("[");
if (this.alunos[0] != null) {
    builder.append(this.alunos[0]);
    return "[]";
}
for (int i = 1; i < this.alunos.length; i++) {
    if (this.alunos[i] == null) break;
    builder.append(", ");
    builder.append(this.alunos[i]);
}
builder.append("]");
return builder.toString();

I put in the Github for future reference.

I also printed an extra item, fixed it.

Then I check if there is at least one item and have it printed out (you have to print it out if there also).

Then I try to see the rest (in the loop) if it is not null.

As I already printed the first item (the 0 no array), I don’t need to print again, so I start at 1.

This separation of the first item is necessary because of the comma. Of course it could have started from 0 and go to the length - 1 not to print the last one (the last one is always the length - 1, since it starts from scratch, many people confuse this, the last would only be exactly the length if the array start from 1.

This is not even computation, it is basic mathematics, but as the comparison operator used is "less than", it already takes the latter) and then would have to print the latter separately (with the if to avoid the null).

It can still be done before or after, I prefer before, because if the first is null I can kill the rest, if it is guaranteed that after finding a null, all will be. In real codes, could do a function to take care of it.

If you had a control of the amount of items in the array, could kill the execution within itself for and wouldn’t even need the if.

I’d take those off this that are completely unnecessary.

There are other minor problems in the code.

Browser other questions tagged

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