我正在尝试编写一个返回整数的静态方法,将二维整数数组作为参数,并返回二维数组(锯齿状数组)中所有元素之和最大的行的索引。一路上出了点问题,我仍在试图找出答案。请帮忙?
这是代码:
public static int findMaxRow(int[][] maxRows){
newI= 0;
newJ= 0;
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
`` if( newI > newJ){
return newI;
else {
}
}
}
}
最佳答案
您永远不会定义 newI
或 newJ
的类型,这可以通过在其声明之前加上其预期类型(即 int
)来修复。在 if 语句之前还有两个“`”,并且在 else 语句之前缺少右括号“}”。但这些只是语法错误。修复这些错误后,您会发现您的方法没有返回所需的结果。
查看您的代码,特别是 for 循环。
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
// other stuff
}
}
假设 maxRows.length 等于 3。这意味着外循环将从 0 运行到 2,因此 newI 将等于 3。同时,对于外循环的每次迭代,内循环将迭代 3 次。所以 newJ
最终将等于 9。这不是对数组元素求和的正确方法。更好的方法是迭代外循环中的数组并对内循环中的元素求和,然后进行比较以完成外循环。就像这样:
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
这是您想要实现的目标的示例。
public class RowSums {
public static void main(String[] args) {
int[][] test = { {1, 5, 7, 0, 9} , {2, 4, 5, 6, 7} , {9, 2, 0, 12, 8, 3} };
System.out.println(printRows(test));
System.out.println("The row with the largest sum is row "
+ findMaxRow(test));
}
public static int findMaxRow(int[][] maxRows){
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
}
public static String printRows(int[][] rows) {
StringBuilder s = new StringBuilder("Rows and their sums:\n");
int sum;
for(int x = 0; x < rows.length; x++) {
s.append("Row [" + x + "] = [ ");
sum = 0;
for(int y = 0; y < rows[x].length; y++) {
s.append(rows[x][y] + " ");
sum += rows[x][y];
}
s.append("]\n");
s.append("Row [" + x + "]'s sum is " + sum + "\n");
}
return s.toString();
}
}
输出:
Rows and their sums:
Row [0] = [ 1 5 7 0 9 ]
Row [0]'s sum is 22
Row [1] = [ 2 4 5 6 7 ]
Row [1]'s sum is 24
Row [2] = [ 9 2 0 12 8 3 ]
Row [2]'s sum is 34
The row with the largest sum is row 2
关于java - 静态方法和锯齿状数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27977828/