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.