How to check if vector fields are null?

-1

I am building a program, which should check initially if the array of type (Class) is null. My class has the get and set method, as well as the with and without default constructors. However, when the program initializes, the values of each cell in my array should be null for the ordered filling of the data.

But it is precisely at this point that where error occurs.

If I put my vetor[i] == null , the program jumps to the end and does not execute the command.

For the execute command I'm putting vetor[i] != null , but this way I'm overwriting some data.

How do I solve it?

public void Insere(){

    for( int  i = 0; i < estacionamento.length;i++){

          estacionamento[i] = new Veiculo();

        if(estacionamento[i] != null){

         estacionamento[i].setPlaca(JOptionPane.showInputDialog("informe a placa do veiculo"));
         estacionamento[i].setModelo(JOptionPane.showInputDialog("informe o modelo do veiculo"));



        }else{
        JOptionPane.showMessageDialog(null, " não ha vagas no estacionamento");
        } break;
    }
}
    
asked by anonymous 14.06.2018 / 23:16

1 answer

0

Your intentions with the code are confusing.

  

My class has the get and set method, as well as the default and non-standard constructors. However, when the program initializes, the values of each cell in my array should be null for the orderly completion of the data.

You are planning to use setPlaca and setModelo but want to initialize the array with null values. This is not possible, you need to have the instance of a Vehicle in each position of the array.

Still, I believe you are planning to have the following code. First, to simulate the array with null values:

// Simulando a inicialização de um array com valores nulos.
Veiculo[] estacionamento = new Veiculo[3];
estacionamento[0] = null;
estacionamento[1] = null;
estacionamento[2] = null;

And the code in question:

for( int  i = 0; i < estacionamento.length;i++){

  if(estacionamento[i] == null){
    estacionamento[i] = new Veiculo(); //faltou instanciar Veiculo
    estacionamento[i].setPlaca(JOptionPane.showInputDialog("informe a placa do veiculo"));
    estacionamento[i].setModelo(JOptionPane.showInputDialog("informe o modelo do veiculo"));

  } else {
    JOptionPane.showMessageDialog(null, " não ha vagas no estacionamento");
  } 
  break;
}
    
15.06.2018 / 00:17