1

我正在制定一个课程计划,但我被卡住了。当我尝试编译以下代码时,我收到变量未找到错误。请帮忙!

public class RingBuffer 
{
    public RingBuffer(int capacity){
        double[] EmptyBuffer = new double[capacity];
        System.out.print(EmptyBuffer.length);

    }

    public int size(){
        int size = EmptyBuffer.length;
        return size;
    }

请注意,我收到一个错误,即 size() 方法无法找到变量 EmptyBuffer。

4

2 回答 2

3

您可能应该将其设为一个字段,也就是一个实例变量:

public class RingBuffer 
{
    private double[] emptyBuffer;

    public RingBuffer(int capacity){
        emptyBuffer = new double[capacity];
        System.out.print(EmptyBuffer.length);
    }

    public int size(){
        int size = emptyBuffer.length;
        return size;
    }
}

这将emptyBuffer在您的课堂上提供,即以任何其他方法。

于 2013-05-03T18:35:52.487 回答
0

将数组作为参数传递给您的size()方法,就像您所做的那样capacity

int size(double[] EmptyBuffer){
    int size = EmptyBuffer.length;
    return size;
}

然后:

double[] EmptyBuffer = new Double[capacity];
int size = size(EmptyBuffer); // make call to size passing the array
                              // as an argument
System.out.print(size);
于 2013-05-03T18:32:39.613 回答