0

I want to fill a table with in 1st row the index and in 2nd row an element generated on a uniform law. To follow the steps of my work I did a non-executable file:

import java.util.Random;

public class CSignal {
    private int N, V;
    private double[][] tabSig;
    public double k;

    public CSignal() {
        V = 4;
        N = 10;

        Remplit();
    }

    public void Remplit() {
        for (int i = 0; i < N; i++) {
            tabSig[0][i] = i;
            Random e = new Random();
            k = e.nextDouble();
            tabSig = new double[2][2];
            this.tabSig[1][i] = k * V;
        }
    }

    public int get_N() {
        return N;
    }

    public int get_V() {
        return V;
    }

    public double[][] get_tab() {
        return tabSig;
    }

    public void Affiche() {
        System.out.println(tabSig);
    }

}

and then the executable:

public class TP {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CSignal signal;
        signal = new CSignal();
        signal.Affiche();
    }
}


When i try this prog I got the following error:

Exception in thread "main" java.lang.NullPointerException: Cannot load from object array because "this.tabSig" is null
SimonW.
  • 33
  • 6
  • 3
    In java you need to initialize your array, before you use it. tabSig = new double[1,N].. https://www.java67.com/2014/10/how-to-create-and-initialize-two-dimensional-array-java-example.html – Beri Jan 02 '21 at 19:04

1 Answers1

1

In general NPE mean you are executing an action on a reference that point to null (nothing).

In your example you have a 2D array called tabSig. In the constructor you are trying to populate it (calling method Remplit), but you have not initialized it. So NPE will be thrown on lines:

tabSig[0][i]= i;
tabSig[1][i]= k*V;

So in order to avoid it, you need to initialize it before this method is called. You must do it in the constructor, as there you are setting N value (length of the second dimension):

public CSignal(){
    V=4;
    N=10;
    tabSig = new double[2,N];
    Remplit();
}

If you want to print the array:

for (int i = 0; i < tabSig.length; i++)
     for (int j = 0; j < tabSig[i].length; j++) 
           System.out.print(tabSig[i][j] + " "); 
Beri
  • 11,470
  • 4
  • 35
  • 57
  • thx for your help, following your advice i add `tabSig = new double[2][N];` in my constructor and when i run my prog i got no error but it return this `[[D@7de26db8` i expected to get the array – SimonW. Jan 02 '21 at 19:16
  • 2
    @SimonW. refer to https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – Abra Jan 02 '21 at 19:20