-2

I'm trying to define an array of a user defined number of elements (degrees) and then a method which allows the user to set an element (coefficient) one at a time.

class Polynomial 
{

    public Polynomial(int degree)
    {
        double[] coef = new double[degree];
    }

    public double[] setCoefficient(int index, double value) 
    {
        coef[index] = value; //coef was set in the constructor
        return coef;
    }
}

I'm getting a compilation error in coef[index] = value;.

Eran
  • 387,369
  • 54
  • 702
  • 768
Matt
  • 59
  • 6
  • read this link to understand variable scopes in java. https://www.tutorialspoint.com/java/java_variable_types.htm – vsbehere Jun 22 '17 at 12:00
  • Simple: don't use a variable, but a **field**. This is really super basic stuff. Although you got a nice answer - please understand that this site is not about again and again explaining the same basics. Don't assume SO is a **replacement** for you reading books / following tutorials. – GhostCat Jun 22 '17 at 12:12

2 Answers2

8

You defined the coef array as a local variable of your constructor, which means it cannot be used anywhere else.

You have to define it as an instance member in order to access it from other methods:

class Polynomial {

    private double[] coef; // declare the array as an instance member

    public Polynomial(int degree) 
    {
        coef = new double[degree]; // initialize the array in the constructor
    }

    public double[] setCoefficient(int index, double value) 
    {
        coef[index] = value; // access the array from any instance method of the class 
        return coef;
    }

}

Note that returning the member variable coef in setCoefficient would allow the user of this class to mutate the array directly (without having to call the setCoefficient method again), which is not a good idea. Member variables should be private and should only be mutated by methods of the class that contains them.

Therefore I'd change the method to:

public void setCoefficient(int index, double value) 
{
    // you should consider adding a range check here if you want to throw
    // your own custom exception when the provided index is out of bounds
    coef[index] = value;    
}

If you need access to elements of the array from outside the class, either add a double getCoefficient(int index) method that returns an individual value of the array, or add a double[] getCoefficients() method that would return a copy of the array.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

this is a scope issue...

public Polynomial(int degree){
     double[] coef = new double[degree];
}

because coef cease to be accessible as soon as the constructor returns, so no method can get that object never...

Do instead:

class Polynomial {
    private double[] coef;

    public Polynomial(int degree) {
        coef = new double[degree];
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97