需要编写名为clearStacks()的方法,该方法将最近创建的机器人向前移动,直到它到达一面墙,拾取它所经过的所有蜂鸣器。该方法不应返回任何值 并且不带任何参数。 它还有一个副作用:该方法会打印机器人在每个堆栈中拾取的蜂鸣器数量。假设一行中有 3 个堆栈,输出可能如下所示:
蜂鸣器:4 蜂鸣器:1 蜂鸣器:7
我的问题是我无法写出机器人在每个堆栈中拾取了多少个蜂鸣器。仅总量。我是Java新手.. 我的代码:
void clearStacks() {
int beepers=0;
while(isSpaceInFrontOfRobotClear()) {
moveRobotForwards();
while(isItemOnGroundAtRobot()) {
pickUpItemWithRobot();
++beepers;
println(beepers);
}
}
}
最佳答案
在检查堆栈之前,您需要重置计数。然后,您需要使用条件语句来查看在清除堆栈(或确定堆栈不存在)后是否拾取任何蜂鸣器。
void clearStacks() {
int beepers=0;
while(isSpaceInFrontOfRobotClear()) {
moveRobotForwards();
/* Reset the count of beepers. */
beepers = 0;
/* Pick up any beepers at current spot. */
while(isItemOnGroundAtRobot()) {
/* Pick up beeper, and increment counter. */
pickUpItemWithRobot();
++beepers;
}
/* Check to see if we picked up any beepers.
* if we did, print the amount.
*/
if(beepers > 0){
println(beepers);
}
}
}
关于java - 在Java中计算堆栈中的蜂鸣器数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19507836/