這是我的解決方案。 我的代碼:Java中的返回聲明
boolean pickUpNBeepersCheckIfAll(int beeper) {
int counter=0;
while(beeper>counter) {
pickUpItemWithRobot();
counter++;
}
return false;
}
應該有什麼問題在這裏,但我不能找到一個錯誤..
這是我的解決方案。 我的代碼:Java中的返回聲明
boolean pickUpNBeepersCheckIfAll(int beeper) {
int counter=0;
while(beeper>counter) {
pickUpItemWithRobot();
counter++;
}
return false;
}
應該有什麼問題在這裏,但我不能找到一個錯誤..
的問題是行動的錯誤的順序採取
int counter=0; //set conter to 0
while(beeper>counter) {
pickUpItemWithRobot();
counter++; //increment counter e.g. it will be 1 in the first loop
if(counter==0) return true; //never true...
好, counter++
是郵政運營商,但,這意味着在評估表達式後完成 - 而不是循環完成後。所以下一個表達式會看到新的值:例如1爲第一次迭代...
boolean pickUpNBeepersCheckIfAll(int beeper) {
for (i = 0; i = beeper; i++ {
try {
pickUpItemWithRobot();
} catch (ItemNotFoundException e) {
return false;
}
}
return true;
}
在您的版本計數器永遠不會0每增加一個循環。
顯然你pickUpItemWithRobot()方法將需要拋出異常,如果它用完了蜂箱。
OP指出有足夠的Beepers安全地執行循環,所以ItemNotFoundException永遠不會被拋出。 – JTMon
boolean pickUpNBeepersCheckIfAll(int beeper) {
int counter=0;
while(beeper>counter) {
pickUpItemWithRobot();
counter++;
}
return true;
}
這是你尋找的東西嗎?
沒有。還有一個錯誤。 – user2817366
從我們所知,這應該是正確的版本。也許使用for循環而不是while。這也清楚地表明pickUpNBeepersCheckIfAll沒有辦法返回false。 – Alex
是什麼樣的?我認爲你需要從方法「pickUpItemWithRobot()」返回類似布爾值的東西。如果pickUpItem成功發生,那麼你可以做下一個計數。 –
您擁有的方法將始終返回false,因爲計數器在檢查時永遠不會爲0。你說如果沒有更多的物品需要拾取,但你從不檢查這種情況,你希望方法返回false。你也說有足夠的提示來確保pickUpItemWithRobot()永遠不會失敗。你必須有尋呼機總數的地方(我現在假設pickUpItemWithRobot()返回左傳呼機的號碼您希望是這樣的:
boolean pickUpNBeepersCheckIfAll(int beeper) {
int beepersLeft;
for (i = 0; i < beeper; i++ {
beepresLeft = pickUpItemWithRobot();
}
return beepersLeft > 0;
}
如果pickUpItemWithRobot()不能返回傳呼機的號碼離開然後返回語句應該是服用點,如:??
return getNumberOfBeeprsLeft() > 0;
「應該有什麼錯在這裏,但我不能找到一個錯誤。」怎麼了怎麼了預期的結果 –
如果有幫助,反會從不= 0,所以這個函數永遠不會返回true – Rawrgramming
對於初學者計數器== 0永遠不會計算爲真 – Leon