user2484149 user2484149 - 6 months ago 20
Java Question

printing a two dimensional matrix (array) java

I need to print this in the correct two dimensional array format. SOmething is wrong. Need the print from the method. My output is what seems to be an infinite loop.

import java.util.Scanner;
public class hw3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is the dimension of your matrix?");
int matrixdim = input.nextInt();
double[][] matrix = new double[matrixdim][matrixdim];

System.out.println("Enter " + matrixdim + " rows, and " + matrixdim + " columns." );
Scanner input1= new Scanner(System.in);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++)
matrix[row][column] = input1.nextDouble();
}
System.out.println("Your original array:");

System.out.println(printArray(matrix));
}
public static double printArray(double matrix[][]){
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;column++) {
System.out.println(matrix[row][column] + " ");
}
System.out.println();
}
return printArray(matrix);

Answer

As I told you in my previous answer invoking same method again return printArray(matrix); at the end of your method can lead to invoking it again (and again) until StackOverflow error.

Change return type to void. Now your method can look like

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

or even better

public static void printArray(double matrix[][]) {
    for (double[] row : matrix) 
        System.out.println(Arrays.toString(row));       
}