Sample Solution Code for Exercise: charge! is wrong
class ChargingRobotDemo {
public static void charge(SimpleRobot r, int maxDist) {
int i = 0;
while (i < maxDist && !r.blocked() ) {
r.forward();
}
}
public static void main(String args[]) {
SimpleRobot r = new SimpleRobot();
r.forward();
r.right();
charge(r, 3);
r.left();
charge(r, 20);
}
}
in the charge method variable i is declared and initialized, but never user.
for meeting the maxDist
condition the i should be incremented or madDist
needs to be decremented
public static void charge(SimpleRobot r, int maxDist) {
int i = 0;
while (i < maxDist && !r.blocked() ) {
r.forward();
i++;
}
}
.
public static void charge(SimpleRobot r, int maxDist) {
while (maxDist-- > 0 && !r.blocked() )
r.forward();
}