类变量不会改变

时间:2019-10-16 15:21:23

标签: java

我的代码如下:

public class Boxes {

    float length = 0;
    float width = 0;
    float height = 0;

    float fmax = (this.getVol() / 40000);
    int max = (int) fmax;

    String[] items = new String[max];

    public float getVol() {

        return length*width*height;

    }

}

当我有此类的实例并且将变量“ length”,“ width”和“ height”设置为非零值时,变量“ fmax”将不会更改。相反,我注意到它默认使用了在类中分配的值,全为0。

2 个答案:

答案 0 :(得分:0)

使用Boxes时,您会这样做:

Boxes boxes = new Boxes();

此时boxes的状态为

  

length = 0;宽度= 0;高度= 0; fmax =(0/40000);

因为长度,宽度和高度都用0初始化,然后是getVol() = 0。因此,fmax=0首先。

现在让我们假设您更改以下值:

boxes.length = 1;
boxes.height = 1;
boxes.width = 1;

此操作不会更改boxes.fmax,因为它已初始化为0并且不再调用getVol。如果要更改它,可以改为使用函数getFmax()

float getFmax() {
    return this.getVol() / 40000;
}

此函数每次都会返回一个不同的值,调用getVol()

答案 1 :(得分:0)

将变量分配给数学运算时,将只计算一次。如果要在数学运算中更改数字之一时更改它,则需要重新分配它。代替使用变量,请尝试使用此函数,该函数将在每次需要时重新计算fmax值。

public float getFmax() {
    return this.getVol() / 40000;
}