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,895
  • 15
  • 65
  • 121
  • by marking `emptyBuffer` in the class declaration as `static`, the problem can be secured better I guess. – Sushim Mukul Dutta May 03 '13 at 18:43
  • @Mario De Schaepmeester the code compiles fine with variable as a `static` , I will be glad if you can explain a bit about what will be the problem. – Sushim Mukul Dutta May 03 '13 at 18:57
  • 1
    @SushimMukulDutta You **cannot** assign a `static` (class) variable in a constructor. See [this question](http://stackoverflow.com/q/5093744/1313143). Maybe you meant `final`? – MarioDS May 03 '13 at 18:59
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
  • 100,477
  • 16
  • 156
  • 200