3 回答

TA貢獻(xiàn)1808條經(jīng)驗 獲得超4個贊
建議:在每個類中添加 getter/setter,以便您可以使用 getter 和 setter 訪問私有變量。
Stone() 是 Jar() 中的私有對象。假設(shè) 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() 將失?。?/p>

TA貢獻(xiàn)1796條經(jīng)驗 獲得超7個贊
Stone 可能還有 Stone 類中的權(quán)重屬性是私有的。為了正確使用它們,我建議您為您的類實現(xiàn) getter 方法。實現(xiàn) getter 后,您可以使用如下方式調(diào)用它們:
jar1.getStone().getWeigth()
其中 getStone() 是 Jar 類中的 getter,getWeight() 是 Stone 類中的 getter。

TA貢獻(xiàn)1811條經(jīng)驗 獲得超6個贊
您需要Stone通過添加 getter 來公開權(quán)重
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;
}
假設(shè) Jar 對象和 Chess 對象永遠(yuǎn)不為 null
添加回答
舉報