Search code examples
javakarel

Count beepers in stacks in Java


Need to write method called clearStacks() that moves the most recently created robot forward until it reaches a wall picking up all beepers at it goes. The method should return no value and take no parameters. It also has a side-effect: the method prints how many beepers the robot picked up in each stack. Supposing there were 3 stacks on a row, the output might look like this:

Beepers: 4 Beepers: 1 Beepers: 7

My problem that I can not write how many beepers the robot picked up in each stack. Only overall amount. I am new in Java.. My code:

void clearStacks() {
int beepers=0;
while(isSpaceInFrontOfRobotClear()) {
    moveRobotForwards();
    while(isItemOnGroundAtRobot()) {
        pickUpItemWithRobot();
        ++beepers;
        println(beepers);
    }
}
}

Solution

  • Before checking for a stack, you'll want to reset your count. You'll then need to use a conditional statement to see if any beepers were picked up after clearing a stack (or determining that a stack was not there).

    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);
            }
        }
    }