Skip to content
Advertisement

Java – generate and rotate matrix

recently I’m trying to learn Java a bit and currently, I’m working on a simple program that should generate a matrix and then rotate it. I’m stuck at the first part. What exactly is the problem? The logic of my code seems to be fine, but anyway program is returning not what I would expect. The code:

import java.util.Scanner;

public class MatrixRotation {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.print("Please, enter matrix size: ");
    int size = in.nextInt();
    double[][] matrix = generateMatrix(size);

    System.out.println(matrix);
}

private static double[][] generateMatrix(int size) {
    double[][] matrix = new double[size][size];
    for (int row = 0; row < size; row++){
        for (int column = 0; column < size; column++){
            matrix[row][column] = (row * 10 + column) / 10.0;
        }
    }
    return matrix;
}

private void printMatrixToConsole(double[][] matrix) {
    for (int row = 0; row < matrix.length; row++){
        for (int column = 0; column < matrix.length; column++){
            System.out.print(matrix[row][column] + "");
        }
        System.out.println("");
    }
}

Output:

Please, enter matrix size: 4

Initial matrix = [[D@34c45dca

Process finished with exit code 0

I’ve tested my code using it outside methods and it works perfectly fine but for some reason, while in methods it’s giving me that weird line of characters.

Could you, please, give me a hint of what is wrong?

Thanks!

Advertisement

Answer

What your seeing in the console is the object reference of the two dimensional array rather than the values it contains. The following statement is the culprit: System.out.println(matrix); if you want print the contents of the matrix you’ll have to call the utility method you’ve already created from the main method passing in the two dimensional array.

Advertisement