【问题标题】:boolean trouble from different class来自不同类的布尔问题
【发布时间】:2016-10-26 19:50:30
【问题描述】:

对于我的作业问题,它是一个带有签名public int applyNutrientCoefficient() 的方法,它计算Pool 中的哪个Guppies 死于营养不良,并返回死亡人数。

使用Iterator<Guppy> 迭代Pool 中的guppiesInPool。对于每个Guppy,使用Random 方法nextDouble() 生成一个介于0.0 和1.0 之间的不同随机数。如果这个随机生成 数量大于池的营养系数,杀死Guppy 通过在Guppy 中设置适当的布尔字段。请注意,这 方法不会从池中移除任何死的孔雀鱼,它只会杀死 他们。不要做任何其他事情。

我有两门课,一门是Guppy 一门是Pool 在我的孔雀鱼课上,我做了一个布尔值 -

private boolean isAlive{}
public boolean getIsAlive(){ 
    return isAlive
}

在我的 Pool 课上......

public int applyNutrientCoefficient() 

int deathCount = 0

Iterator<Guppy> it = guppiesInPool.iterator()

while (it.hasNext() ) 

Guppy guppyOne = it.next()

    if (randomNumberGenerator.nextDouble() > nutrientCoefficient) 
    if (guppyOne.isAlive() ) 
    guppyOne.setAlive(false)
    deathCount++

    return deathCount

我得到的错误信息是找不到符号 - 方法isAlive()

有人可以帮忙吗

【问题讨论】:

  • 一团糟,这不是有效的 java 代码。您缺少分号和括号。

标签: java boolean


【解决方案1】:

你的语法似乎有点不对劲。应该是

private boolean isAlive; //private field, not a method.
public boolean getIsAlive() {  //public getter method.
    return isAlive;
}
public void setIsAlive(boolean isAlive) { //public setter method
    this.isAlive = isAlive;
}

那么,

public int applyNutrientCoefficient() {
    int deathCount = 0;
    Iterator it = guppiesInPool.iterator();
    while (it.hasNext()) {
        Guppy guppyOne = it.next();
        if (randomNumberGenerator.nextDouble() > nutrientCoefficient) {
            if (guppyOne.getIsAlive()) {
                guppyOne.setIsAlive(false);
                deathCount++; // should be inside the if-block i suppose?
            }
        }
    }

    return deathCount;
}

还要确保使用分号和花括号,否则编译器会报错。

【讨论】:

    【解决方案2】:

    您必须通过您提供 getIsAlive() 的公共 getter 访问 isAlive 私有字段

    在池类中

    if (randomNumberGenerator.nextDouble() > nutrientCoefficient) 
    if (guppyOne.isAlive() ) 
    guppyOne.setAlive(false)
    deathCount++
    
    return deathCount
    

    一行

    if (guppyOne.isAlive() )
    

    应该是

    if (guppyOne.getIsAlive() )
    

    与 setter 相同:您需要为 Guppy 类提供一个 setter 并使用它

    public void setIsAlive(boolean alive){
    this.isAlive = alive}
    

    最终结果应该是

    if (randomNumberGenerator.nextDouble() > nutrientCoefficient) 
    if (guppyOne.getIsAlive() ) 
    guppyOne.setIsAlive(false)
    deathCount++
    
    return deathCount
    

    【讨论】:

    • 我确实这样做了,我放了 getIsAlive() 但由于某种原因仍然给了我同样的错误。我如何将私人 isAlive 公开?我做了 public boolean getIsAlive() { return isAlive;
    • 您还必须调用 getIsAlive() 公开访问私有isAlive 字段的当前值。顺便说一句:即使它是公开的 isAlive() 也不会编译,因为它不是方法而是字段。
    • 问题是你试图在池类中直接访问 isAlive if (guppyOne.isAlive() ) 当你应该使用 getter if (guppyOne.getIsAlive() )
    • 对不起,我只是困惑。我该怎么称呼它?
    • if (guppyOne.isAlive() )
    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多