return方法找不到符号

时间:2013-09-18 13:57:39

标签: java methods

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"

3 个答案:

答案 0 :(得分: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

然而你有另一个问题......你将值添加到一个整数...我不确定你是否想要它,即使你需要得到返回整数,我将它们添加为双精度数,并返回一个整数...

答案 1 :(得分: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变量,并在该块外部访问它 你应该在循环开始之前初始化它

答案 2 :(得分: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;
}