有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有人能告诉我如何将这个数组传递到我的主方法中,以便它打印出来吗?

我试图传递我的数组,但它不会打印sumAllColumnsRows,我搜索了很多站点,我不知道如何打印代码。正在从下面的方法传递

public static void main(String[] args){

    Scanner input= new Scanner(System.in);

    System.out.print("Enter dimension of an nxn matrix ");
    int x=input.nextInt();
    double[][] nxn=new double[x][x];
    for(int i=0;i<x;i++) {
        System.out.print("Enter row " + (i) + ": ");
        for(int j=0;j<x;j++){
            nxn[i][j]=input.nextDouble();
        }
    }
    System.out.println(sumAllColumnsRows(m, column, rowColumn));
}

public static double sumAllColumnsRows(double[][] m, boolean column, int rowColumn)
{
    double total=0;
    for (int col = 0; col < m[0].length; col++) {
        int colSum = 0;
        for (int row = 0; row < m.length; row++) {
            colSum += m[row][col];
        }
        System.out.println("Sum of the elements at col " + col + " is: " + colSum);
    }

    for (int row = 0; row < m.length; row++) {
        int rowSum = 0;
        for (int col = 0; col < m[row].length; col++) {
            rowSum += m[row][col];
        }
        System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
    }
    return total;
}

共 (2) 个答案

  1. # 1 楼答案

    您没有添加到sumAllColumnsRows中的total变量。它将始终返回0

    public static double sumAllColumnsRows(double[][] m, boolean column, int rowColumn) {
        double total = 0;
        for (int col = 0; col < m[0].length; col++) {
            int colSum = 0;
            for (int row = 0; row < m.length; row++) {
                colSum += m[row][col];
            }
            total += colSum;
            System.out.println("Sum of the elements at col " + col + " is: " + colSum);
        }
    
        for (int row = 0; row < m.length; row++) {
            int rowSum = 0;
            for (int col = 0; col < m[row].length; col++) {
                rowSum += m[row][col];
            }
            total += rowSum;
            System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
        }
        return total;
    }
    
  2. # 2 楼答案

    好的,你的问题可能已经在这里确定了,但我想你可能还有其他问题。第一:

    double[][] nxn=new double[x][x];
    ...
    System.out.println(sumAllColumnsRows(m, column, rowColumn));
    

    您正在定义变量non,但正在传递m。您也没有变量column和rowColumn。我想这段代码无法编译

    但是,请注意,sumAllColumnsRows实际上并没有使用这两个参数

    来自javac的错误消息应该有助于解决这个问题