有个小问题,有个程序是读入一系列整数到数组data中,然后加减输出结果,比如,输入的是1,2,3,4,5,6,7,8,那么就计算1-2+3-4+5-6+7-8,这样的结果输出,程序写出如下,可有一点疑问,如果将add函数中的三处data.length换成DATA_LENGTH,为什么会报错呢
public class DataSet
{    
private double[] data;
private int datasize;

public DataSet()
{
final int DATA_LENGTH=100;
data=new double[DATA_LENGTH];
datasize=0;
}

public void add(double x)
{
if(datasize>=data.length)//这里的data.length能换成DATA_LENGTH吗 {
  double[] newData = new double[2*data.length];//这里的data.length能换成DATA_LENGTH吗
  System.arraycopy(data,0,newData,0,data.length);//这里的data.length能换成DATA_LENGTH吗   data=newData;
}
data[datasize]=x;
datasize++;
}

public double alteringSum()
{
double sum = 0;
for(int i = 0;i<=datasize;i++)
{                   
    if(i%2==0)
    {
     sum=sum+data[i];
    }
    else if(i%2==1)
    {
     sum=sum-data[i];
    }
}
return sum;
}
}

解决方案 »

  1.   

    作用域不同,DATA_LENGTH的作用域只在public DataSet()
    函数里。
      

  2.   

    After the constructor DataSet(), data.length equals 100. Its value is set to DATA_LENGTH. When use the method add, when the array is full, this case datasize = 100, then the array is copied to a new array with the size double.This time around, the data.length will be 200, and then when the datasize become 200, then the array is copied to a new array and the data.length will be 400 so far and so on.DATA_LENGTH is only used to set the initial array size. The array then grows dynamically and double the size every time it becomes full.
      

  3.   

    在构造函数之前定义final变量
      

  4.   

    不能换,因为DATA_LENGTH在add()没定义,就算能换也不要啊,那样范围小。。
      

  5.   

    作用域不同,所以在add中不能用
      

  6.   

    final int DATA_LENGTH=100定义成全局变量
      

  7.   

    的确是作用域不同,DATA_LENGTH的作用域只在public DataSet()中有效,因为你是在DataSet()方法里面定义的,是局部变量,