Mounts a vector with 5 students, in the fifth student this vector multiplies by 2, being able to give input to 10

Asked

Viewed 54 times

-4

private Aluno alunos[];
private int ultimaPosicao;
public int tam=5;
/**
 * Construtor 
 */
public VetorDeAlunos(){
    alunos = new Aluno[tam];
    ultimaPosicao = 0;
} 
/**
 * Metodo para inserir aluno na lista. Este metodo insere o aluno na ultima posiçao
 * disponivel
 * @params  Aluno aluno - Aluno a ser inserido no vetor.
 * 
 */
public void inserir(Aluno aluno){                
    //o array estoura aqui    
    this.alunos[ultimaPosicao] = aluno;
    ultimaPosicao++;        
}

//in this algorithm has several test classes other buttons and etc... (DONE IN GREENFOOT)

  • 1

    What’s your question? What’s wrong with the code?

  • the array pops into this.students[last] = student;

2 answers

0


Expanding array size is impossible.

What you can do is reassign the variable alunos with a new larger dimension array based on old values through the method copyOf() class java.util.Arrays:

public void inserir(Aluno aluno){                
    //o array estoura aqui    
    this.alunos[ultimaPosicao] = aluno;
    ultimaPosicao++;
    if(ultimaPosicao == 5) {
        alunos = Arrays.copyOf(alunos, 10);
    }
}

0

You have to put on an If ultimaPosicao == 5 then

private Aluno alunosnovos[] = new Aluno[10];
alunosnovos = alunos;
alunos = alunosnovos;

Voce reason has to increase the physical space copy the old ones to the new space and then copy back;

You need to grow the space before trying to add new elements or it doesn’t work. Understand?

  • understand friend ,already tried the same ,but does not work , continues with the same error...

Browser other questions tagged

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