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.
– user28595
How do I not print? I tried != null, but it’s not right
– odranoeL
If you tried, you could have asked the question to tell us what’s wrong.
– Maniero