0
public static int rowSum(int[][] d)
{
    for (int i = 0; i < d.length; i++)
    {
        int  sum = 0;
        for (int j = 0; j < d[i].length; j++)
        {
            sum = sum + d[i][j];
        }
    }
    return sum;
}
// says cant find symbol "sum"
4

3 回答 3

6

是的,你试图使用你在一个无效的范围内定义的变量......

public static int rowSum(int[][] d)
{

  for (int i = 0; i < d.length; i++)
  {
     int  sum = 0;      //definition
     for (int j = 0; j < d[i].length; j++)
     {
        sum = sum + d[i][j];
     }
  } //scope of sum variable ends here

  return sum; //not valid access!!! sum is not defined here.
}   

把它放在外面一圈:

public static int rowSum(int[][] d)
{
  int  sum = 0;      //definition
  for (int i = 0; i < d.length; i++)
  {
     for (int j = 0; j < d[i].length; j++)
     {
        sum = sum + d[i][j];
     }
  }    
  return sum; //not valid access!!!
}   //scope of sum ends here

但是您还有另一个问题...您将精度值添加到整数...我不确定您是否想要这样,即使您需要返回整数,我也会将它们添加为双精度,并返回一个整数。 ..

于 2013-09-18T14:00:36.537 回答
0
public static int rowSum(int[][] d) {
for (int i = 0; i < d.length; i++)
{
int  sum = 0;
 for (int j = 0; j < d[i].length; j++)
 {
    sum = sum + d[i][j];
 }
}return sum;
}

您在外部 for 循环块中定义了 sun 变量并在该块之外访问它,您应该在 for 循环开始之前对其进行初始化

于 2013-09-18T14:03:16.640 回答
0

是的,正如 ppeterka66 所说,您必须更改变量的范围。由于块变量对其块可见。所以你需要在 main 方法中定义 sum 。

public static int rowSum(int[][] d)
{

    int sum = 0;

    for ( int i = 0; i < d.length; i++)
    {
        for (int j = 0; j < d[i].length; j++)
        {
            sum = sum + d[i][j];
        }
    }
    return sum;
}
于 2013-09-18T14:06:23.657 回答