[英]Calling static method in main part
How can I call a method in the main method?如何在 main 方法中调用方法?
public class Sum extends ConsoleProgram {
public void run() {
int[][] array = {{32, 4, 14, 65, 23, 6},
{4, 2, 53, 31, 765, 34},
{64235, 23, 522, 124, 42}};
}
public static int sumRow(int[][] array, int row) {
int sum = 0;
for(int col = 0; col < array[row].length; col++) {
sum += array[row][col];
}
return sum;
}
}
I used this option我使用了这个选项
public void run() {
int[][] array = {{32, 4, 14, 65, 23, 6},
{4, 2, 53, 31, 765, 34},
{64235, 23, 522, 124, 42}};
sumRow(); // and this way System.out.println(sumRow);
}
Expected result:预期结果:
144
889
64946⏎
Actual result:实际结果:
You forgot to print something.
public static int sumRow(int[][] array, int row)
this requires a matrix int[][] array
and an integer int row
as inputs.这需要一个矩阵
int[][] array
和一个 integer int row
作为输入。
then it outputs an integer static int
as output.然后它将 integer
static int
输出为 output。
Therefore when you call the function you must write it like so:因此,当您调用 function 时,您必须这样编写:
sumrow(array, row);
And print it out like so:并像这样打印出来:
System.out.println(sumrow(array, row));
As pointed out by @k314159.正如@k314159 所指出的。
To get the output of all three arrays inside the matrix you would have to:要在矩阵中获取所有三个 arrays 的 output,您必须:
System.out.println(sumrow(array, 0));
System.out.println(sumrow(array, 1));
System.out.println(sumrow(array, 2));
And this should output the sum of all three arrays in the matrix.这应该是 output 矩阵中所有三个 arrays 的总和。
Also I would like to point out that int[][]
is a matrix and not an array, so it would be more "correct" to declare it like so:另外我想指出
int[][]
是一个矩阵而不是一个数组,所以像这样声明它会更“正确”:
public class Sum extends ConsoleProgram {
public void run() {
int[][] matrix = {{32, 4, 14, 65, 23, 6},
{4, 2, 53, 31, 765, 34},
{64235, 23, 522, 124, 42}};
}
public static int sumRow(int[][] matrix, int row) {
int sum = 0;
for(int col = 0; col < matrix[row].length; col++) {
sum += matrix[row][col];
}
return sum;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.