我想知道为什么返回iBiggest不会引用if语句中的iBiggest。有没有办法让它成功?我的总体目标是返回一个包含最大总和的数组中的行。该阵列是二维的。
public static int findMaxRow(int[][] arr){
int curMax=0;
//int iBiggest;
for (int i=0; i < arr.length; i++){
int curSum = 0;
for (int j=0; j < arr[i].length; j++){
arr[i][j]+= curSum;
if (curSum>curMax){
curSum=curMax;
int iBiggest = i;
}
}
}
return iBiggest;
}
答案 0 :(得分:0)
您需要扩大变量的范围,以便从您想要返回的位置可见。由于您希望将其返回到for
循环之外,因此应在外部声明:
int iBiggest = 0;
int curMax=0;
for (int i=0; i < arr.length; i++){
int curSum = 0;
for (int j=0; j < arr[i].length; j++){
arr[i][j]+= curSum;
if (curSum>curMax){
curSum=curMax;
iBiggest = i;
}
}
}
return iBiggest;
}
答案 1 :(得分:0)
看看this tutorial。在那里,您将了解到必须在for循环之外声明iBiggest
:
// function header
{
int curMax = 0;
int iBiggest = 0;
for (int i = 0; i < arr.length; i++){
int curSum = 0;
for (int j = 0; j < arr[i].length; j++){
arr[i][j]+= curSum;
if (curSum > curMax){
curSum = curMax;
iBiggest = i;
}
}
}
// Has iBiggest to be declared inside the same scope!
return iBiggest;
}
答案 2 :(得分:0)
我通常在我的方法的顶部声明我的变量,以便这样的事情永远不会发生。你需要让你的变量在for之外,这样return语句可以&#34;看&#34;它。希望这有帮助!
public static int findMaxRow(int[][] arr){
int curMax=0;
int iBiggest = 0;
int curSum = 0;
for (int i=0; i < arr.length; i++){
curSum = 0;
for (int j=0; j < arr[i].length; j++){
arr[i][j]+= curSum;
if (curSum>curMax){
curSum=curMax;
iBiggest = i;
}
}
}
return iBiggest;
}