1

I have a basic java question - I have an array and I need to do a multiplication of all the elements, so for input:

1 2 3

The output will be:

1  2  3 
2  4  8 
3  6  9

How can I print the 2d array from the main ?
PS - I want the method just to return the new 2d array, without printing it ( I know I can do it without the method and and print mat[i][j] within the nested loop)

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        System.out.println(matrix(array));
    }

    public static int[][] matrix(int[] array){
        int[][] mat = new int[array.length][array.length];
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                mat[i][j] = array[i] * array[j];
            }
        }

        return mat;
    }
}
Niminim
  • 668
  • 1
  • 7
  • 16
  • 1
    "Enter" does work here. Put two spaces at the end of a line and you get the Enter you want. It also surprised me that it was that way. – Anonymous Coward Sep 11 '15 at 18:24
  • Zong - System.out.println(Arrays.deepToString(array)); doesn't work here.... I already tried it before posting – Niminim Sep 11 '15 at 18:27

1 Answers1

2

You have to print all the individual elements of the array, because if you just try to print an array, it will print all kinds of other stuff you might not want to see. So you cherry pick out what you want, and format it a little. In the below code you have each element printed, seperated on a space until it reaches a new row, where it then jumps to a new line.

int[][] matrixArray = matrix(array);

for(int i = 0, i < matrixArray.length; i++) {
    for(int j = 0; j < matrixArray[0].length; j++) {
        System.out.print(matrixArray[i][j] + " ");
    }
    System.out.println();
}
Mildan
  • 116
  • 2
  • 7