1

I am working on a program for class and I am stuck. When I try to compile the following code I receive and variable not found error. please help!

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;
    }

please note that I am getting an error with the size() method not being able to find the variable EmptyBuffer.

  • `EmptyBuffer` is a local variable to your constructor. Once the constructor finish it goes out of scope (it no longer exists). – andre May 03 '13 at 18:36

2 Answers2

3

You should probably make that a field, aka an instance variable:

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;
    }
}

This will make emptyBuffer available throughout your class, i.e. in any other method.

MarioDS
  • 12,489
  • 14
  • 63
  • 120
0

Pass the array as an argument to your size() method like you've done with capacity:

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

Then:

double[] EmptyBuffer = new Double[capacity];
int size = size(EmptyBuffer); // make call to size passing the array
                              // as an argument
System.out.print(size);
Brad Christie
  • 98,427
  • 16
  • 148
  • 198