1

我需要以正确的二维数组格式打印它。出了点问题。需要从方法打印。我的输出似乎是一个无限循环。

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);
4

4 回答 4

12

正如我在之前的回答中告诉你的那样,在方法结束时再次调用相同return printArray(matrix);的方法可能会导致再次(一次又一次)调用它,直到 StackOverflow 错误。

将返回类型更改为void. 现在你的方法看起来像

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();
    }
}

甚至更好

public static void printArray(double matrix[][]) {
    for (double[] row : matrix) 
        System.out.println(Arrays.toString(row));       
}
于 2013-06-14T23:29:33.453 回答
2

只需在第一个打印调用中 更改println为。print

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不在\n输出末尾打印换行符 ( ),而println. 这就是为什么你得到丑陋的印刷品。

此外,printArray不应该返回一个值,它应该是:

public static void printArray(double[][] matrix)

我认为这就是你得到无限循环的地方。不要返回任何东西 - 不需要,你只是在打印它。

于 2013-06-14T23:27:09.623 回答
1

您缺少 } 并在第二个循环中使用print而不是。println

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();
    }
}
于 2013-06-14T23:28:20.907 回答
-1

你得到了System.out.println(printArray(matrix));,而不是printArray(matrix);因为你的方法得到了打印调用

如上所述 - printvsprintln

于 2013-06-14T23:29:55.603 回答