Java 通过多种方法传递二维数组
我为学校写的程序有点麻烦。本质上,我必须使用多种方法并通过它们传递二维数组。为此,我必须在方法中使用嵌套for循环,但这些方法不允许我返回“total”。你可以在下面看到我使用的方法。下面两种方法运行良好,只有那些带有总变量的方法不行。(是的,我试过用其他名字。)Java 通过多种方法传递二维数组,java,Java,我为学校写的程序有点麻烦。本质上,我必须使用多种方法并通过它们传递二维数组。为此,我必须在方法中使用嵌套for循环,但这些方法不允许我返回“total”。你可以在下面看到我使用的方法。下面两种方法运行良好,只有那些带有总变量的方法不行。(是的,我试过用其他名字。) //每行的方法和 公共静态int行和(int[][]矩阵){ System.out.println(“行总数**********************************************”; 对于(int row=0;r
//每行的方法和
公共静态int行和(int[][]矩阵){
System.out.println(“行总数**********************************************”;
对于(int row=0;row问题在于变量范围,
你的代码在这些地方有缺陷
public static int columnsum(int[][] matrix){
System.out.println("Column Totals************************************");
for (int column = 0; column<matrix[0].length; column++){
int total = 0; // total is defined within the for loop you cannot access it outside the for loop
for (int row = 0; row<matrix.length; row++){
total += matrix[row][column];
System.out.println("The sum of column "+column+" is: "+total);
}
return total; // Java do not know the total variable since it's already got destroyed after the for loop got terminated
}
公共静态int-columnsum(int[][]矩阵){
System.out.println(“列总计*************************************************”;
for(int column=0;columntotal
变量仅在for循环内部可见。在循环外部定义它们。可能重复
public static int columnsum(int[][] matrix){
System.out.println("Column Totals************************************");
for (int column = 0; column<matrix[0].length; column++){
int total = 0; // total is defined within the for loop you cannot access it outside the for loop
for (int row = 0; row<matrix.length; row++){
total += matrix[row][column];
System.out.println("The sum of column "+column+" is: "+total);
}
return total; // Java do not know the total variable since it's already got destroyed after the for loop got terminated
}
public static int columnsum(int[][] matrix){
System.out.println("Column Totals************************************");
int total = 0; // define total here
for (int column = 0; column<matrix[0].length; column++){
for (int row = 0; row<matrix.length; row++){
total += matrix[row][column];
System.out.println("The sum of column "+column+" is: "+total);
}
return total;
}