2

The thing is that I'm trying to print the matrix previously created in the constructor, but seems that it's empty.

Here's the code of the constructor:

public Matrix(int row_col){
    int [][] randomMatrix = new int[row_col][row_col];
    Random rand = new Random();
    if (row_col > 0 && row_col < ROW_LIMIT && row_col < COL_LIMIT)
    for (int i = 0; i < randomMatrix.length; i++) 
     for (int j = 0; j < randomMatrix[0].length; j++)
         randomMatrix[i][j] = rand.nextInt(51);
}

And the code of the method print:

public void print(){
    int row = randomMatrix.length;
    int col = randomMatrix[0].length;
    for(int i=0 ; i < row ; i++)
     for(int j=0 ; j < col ; j++)
        System.out.print(randomMatrix[i][j]);
}

Greetings!

0

3 Answers 3

4

Replace

int [][] randomMatrix = new int[row_col][row_col];

by

this.randomMatrix = new int[row_col][row_col];

The constructor initializes and fills a local variable instead of initializing and filling the instance field used by the print() method.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, now seems to work, but in a strange way. I set the dimension to 2x2, but when I call to the print method, it prints such a huge chain of numbers... do I have something wrong in the constructor?
@Ziitox what else do you expect? you never call System.out.println() or have a "\n" in your output when using your print() method.
1

It looks like randomMatrix is defined directly in the scope of the constructor, and is not being stored in a field of the class.

If you already have a randomMatrix as a field, remove the int[][] in the first line of the constructor method, so you refer to the field instead of declaring a new variable.

Comments

0

It is beacuse you have declared and initialized your array randomMatrix inside your constructor and as soon as the contructor's code is executed your randomMatrix array goes out of scope of print method.

And so when you try to access it in print method there is no such randomMatrix object, so you get NullPointerException

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.