3 回答

TA贡献1808条经验 获得超4个赞
建议:在每个类中添加 getter/setter,以便您可以使用 getter 和 setter 访问私有变量。
Stone() 是 Jar() 中的私有对象。假设 Jar() 中有 getStone() 返回: this.stone; 你可以做
if (jar1.getStone().getWeight() + jar2.getStone().getWeight() + jar3.getStone().getWeight() == chest.combination) //the main problem
还要确保在尝试访问可为 null 的对象中的方法之前检查 null 对象(例如,如果 jar1 Stone 为 null,则 jar1.getStone().getWeight() 将失败)

TA贡献1796条经验 获得超7个赞
Stone 可能还有 Stone 类中的权重属性是私有的。为了正确使用它们,我建议您为您的类实现 getter 方法。实现 getter 后,您可以使用如下方式调用它们:
jar1.getStone().getWeigth()
其中 getStone() 是 Jar 类中的 getter,getWeight() 是 Stone 类中的 getter。

TA贡献1811条经验 获得超6个赞
您需要Stone通过添加 getter 来公开权重
public int getWeight() {
return weight;
}
然后你可以用类似的方法使用它Jar
public int getWeight() {
if (stone == null) {
return 0;
}
return stone.getWeight();
}
那么你的方法就是
public boolean ChestUnlocked() {
if (jar1.getWeight() + jar2.getWeight() + jar3.getWeight() == chest.combination) {
return true;
}
return false;
}
假设 Jar 对象和 Chess 对象永远不为 null
添加回答
举报