Reputation: 31
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);
Upvotes: 1
Views: 43364
Reputation: 124215
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));
}
Upvotes: 12
Reputation: 9775
Just change the println
to print
in the first print call.
public static void printArray(double matrix[][]){
for (...) {
for (...) {
//here just print goes
System.out.print(matrix[row][column] + " ");
}
//at the end each row of the matrix you want the new line - println is good here
System.out.println();
}
}
print
does not print the newline (\n
) at the end of the output, whereas the println
does. That's why you're getting the ugly print.
Also, printArray
should not return a value, it should be:
public static void printArray(double[][] matrix)
I think that's where you're getting your infinite loop. Don't return anything - no need, you are just printing it.
Upvotes: 2
Reputation: 34
you got System.out.println(printArray(matrix));
instead of printArray(matrix);
since your method got print calls in it anyway
and as mentioned above - print
vs println
Upvotes: -1
Reputation: 1845
You are missing a } and use print
instead of println
inside your 2nd loop.
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.print(matrix[row][column] + " ");
}
System.out.println();
}
}
Upvotes: 1