Java constructor with matrix

Asked

Viewed 1,064 times

3

I am learning about constructors in java but I stopped in college exercise that seemed simple, the proposal is to create a constructor class with a matrix, and call it in another class to assign the values to the matrix:

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 someone help me assign the values to the matrix by calling the constructor?

  • The problem is that you need to instantiate the matrix. Example: pop = new int[4][5]

2 answers

2

First let’s get to why you might be getting the NullPointerException:

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

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

Below is a code that I believe would work for you. I couldn’t test the code because I don’t have Java on this machine.

Populace:

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);  
        }
    }        
}
  • Thank you very much, exactly what I needed, improved for my exercises, worked and learned.

  • @Johnnybastos if the two answers helped you, and choose the one that best suits your problem and mark as the solution

1

First you have to see that a constructor has to have exactly the same class name which 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 at the instance the object has to pass the attributes by parameter:

E.x.: This Patient class I created a constructor that takes 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 any argument as the constructor pattern will occur error, then note that at the instance of the object between parentheses there are the two arguments according to each type that will be received by the constructor.

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

Browser other questions tagged

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