Java constructor with array

3

I'm learning about constructors in java but I stuck in the exercise of college that seemed simple, the proposal is to create a class constructor with an array, and call it in another class to attribulate the values to array:

Builder:

public class Populacao {

    public void atualizarPopulacao(int i, int j, int populacao){
        if (i>=0 && i<4 && j>=0 && j<5 && populacao > 0)
            pop[i][j] = populacao;
        }

  }

Main class:

import javax.swing.JOptionPane;

public class Administracao {

    public static void main(String p[]) {

        Populacao pop = new Populacao();

         int i,j;
         int n;

         for (i=0; i<4; i++){
             for(j=0; j<5; j++){
                 n = Integer.parseInt(JOptionPane.showInputDialog("Populacão: " + String.valueOf(i+1) + "\nEstado: " + String.valueOf(j+1)));

                 pop.atualizarPopulacao(i, j, n);

             }
         }



    }

}

But I get the error:

  

Exception in thread "main" java.lang.NullPointerException

Can anyone help me to assign the values to the array by calling the constructor?

    
asked by anonymous 22.03.2016 / 02:14

2 answers

2

First of all, why are you getting NullPointerException :

I think there is some code missing from what you posted, otherwise the code would not compile, but what might be causing this error is not initializing your pop variable used within your atualizarPopulacao method.

If you try to assign a value to its pop[i][j] = populacao; variable but it has not been initialized previously, a NullPointerException will pop.

Below is a code that I believe would work for you. I could not test the code because I do not have Java on this machine.

Population Class:

public class Populacao{
    private Integer[][] matriz; //Declaração da variavel

    /* Construtor da classe Populacao, recebe o numero de cidades e estados
       e cria uma matriz com as dimensões numero de cidades por numero de estados */
    public Populacao(int numeroCidades, int numeroEstados){
        this.matriz = new Integer[numeroCidades][numeroEstados]; //Inicializacao da variavel
    }

    //Atualiza a populacao da cidade no estado.
    public void atualizaPopulacao(int cidade, int estado, Integer populacao){
        this.matriz[cidade][estado] = populacao;
    }

    public int getNumeroCidades(){
        return this.matriz.length;
    }

    public int getNumeroEstados(){
        return this.matriz[0].length;
    }
}

Main:

public static void main(String [] args){
    Integer numeroHabitantes;
    int numeroCidades = 4;
    int numeroEstados = 3;
    Populacao populacao = new Populacao(numeroCidades, numeroEstados);

    for(int i=0; i < populacao.getNumeroCidades(); i++){
        for (int j=0; j < populacao.getNumeroEstados(); j++){
            numeroHabitantes = Integer.parseInt(JOptionPane.showInputDialog("Populacão: " + String.valueOf(i+1) + "\nEstado: " + String.valueOf(j+1)));
            populacao.atualizaPopulacao(i, j, numeroHabitantes);  
        }
    }        
}
    
22.03.2016 / 07:22
1

First you have to see that a constructor has to have exactly the same class name as does not occur in your code and is one of the factors that may be generating the error. Another point is the use of the constructor occurs when you instantiate the object to pass the attributes by parameter:

E.: this patient class I created a constructor that gets two values per parameter.

public class Paciente {

    float peso;
    double altura;

    public Paciente(float peso, double altura) {
        this.peso = peso;
        this.altura = altura;
    }
}

When I instantiate this class in the execution class I already have to pass the arguments to create the object.

e.x.:

public class Principal {

    public static void main (String[] args) {
        Paciente p1 = new Paciente(100f, 1.75);
        Paciente p2 = new Paciente(78f, 1.80);
        Paciente p3 = new Paciente(130f, 1.85);
    }
}

If I do not pass some argument as the constructor pattern will error, then notice that in the instance of the object in parentheses there are both arguments as each type will be received by the constructor.

In your case so that you can create your object you have to follow these rules of constructor creation, generate the array before the creation of the object and do not forget to state in the signature of the constructor the type of parameter that it should receive .

    
22.03.2016 / 05:00