2013-10-22 33 views
1

需要编写一个名为clearStacks()的方法,它将最近创建的机器人向前移动,直到它到达墙上时拾取所有的响应者。该方法不应返回任何值 并且不带任何参数。 它也有一个副作用:该方法打印机器人在每个堆栈中拾取了多少个蜂鸣器。假设有3堆在一排,输出可能是这样的:在Java堆栈中计数响应者

传呼机:4 传呼机:1个 传呼机:7

,我不能写的机器人,有多少传呼机拿起

我的问题每个堆栈。只有总量。我在Java中.. 我的代码是新:

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

回答

2

前检查堆栈,你要重置计数。然后,您需要使用条件语句来查看清除堆栈后是否拾取了任何蜂箱(或确定堆栈不在那里)。

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

也许尝试实现一个数组?您可以使用前3个元素来表示前3个堆栈,然后该值可以表示在每个堆栈中拾取了多少个蜂鸣器。

int[] beepers = new int[3]; 
int count = 0; 
while(isSpaceInFrontOfRobotClear()) { 
    moveRobotForwards(); 
    while(isItemOnGroundAtRobot()) { 
     pickUpItemWithRobot(); 
     beepers[0]++; 
     if (count > #numberOfBeepers) { 
       break; 
     } 
    } 
    for (int i: beepers) { 
      System.out.print(beepers[i] + " ") 
     } 
    } 
} 

让我知道如果这个回答你的问题,或者如果它没有

+0

你可能无法知道将会提前遭遇数堆栈。你也永远不会改变你的数组索引。 – Dev