如何使用在方法中的构造函数中初始化的数组?

问题描述:

我试图定义一个用户定义数量的元素(度)的数组,然后允许用户一次设置一个元素(系数)的方法。如何使用在方法中的构造函数中初始化的数组?

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

我在coef[index] = value;中收到编译错误。

+0

阅读此链接了解java中的变量作用域。 https://www.tutorialspoint.com/java/java_variable_types.htm – vsbehere

+0

简单:不要使用变量,而是**字段**。这真的是超级基本的东西。虽然你有一个很好的答案 - 请理解,这个网站不是一遍又一遍地解释相同的基础知识。不要以为你是阅读书籍/后续教程的替代**。 – GhostCat

您将coef数组定义为构造函数的局部变量,这意味着它不能在其他地方使用。

你必须以从其他方法来访问它来把它定义为一个实例成员:

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

} 

注意,在setCoefficient返回成员变量coef将允许这个类的用户到阵列直接突变(不必再次调用setCoefficient方法),这不是一个好主意。成员变量应该是私有的,只应该由包含它们的类的方法进行变异。

因此我会改变的方法:

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

如果需要访问来自类的外部阵列的元件,无论是添加double getCoefficient(int index)方法,返回该阵列的单独的值,或添加double[] getCoefficients()方法将返回数组的副本

+3

我不知道为什么'setCoefficient'应该返回该字段。值得一提的是。 – Bathsheba

+0

不错。有一个upvote。 – Bathsheba

这是一个范围问题...

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

因为COEF而不再是访问尽快构造函数返回,所以没有方法可以得到目标从来没有......

待办事项相反:

class Polynomial { 
    private double[] coef; 

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

正确的答案,但基本上重复Eran的。 – JacksOnF1re

+0

@ JacksOnF1re几乎总是在他身后20秒.... :-) –

+1

所以20秒就可以在SO的175K声望差距.... –