【问题标题】:Count beepers in stacks in Java在 Java 中计算堆栈中的蜂鸣器
【发布时间】:2013-10-22 02:05:18
【问题描述】:

需要编写一个名为 clearStacks() 的方法,该方法将最近创建的机器人向前移动,直到它到达一面墙,然后拾取所有蜂鸣器。该方法不应返回任何值 并且不带任何参数。 它还有一个副作用:该方法会打印机器人在每个堆栈中拾取了多少个蜂鸣器。假设一行有 3 个堆栈,输出可能如下所示:

蜂鸣器:4 蜂鸣器:1 蜂鸣器:7

我的问题是我无法写出机器人在每个堆栈中拾取了多少个蜂鸣器。只有总量。我是Java新手.. 我的代码:

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

【问题讨论】:

    标签: java karel


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      也许尝试实现一个数组?您可以使用前 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] + " ")
              }
        }
      }
      

      如果这回答了您的问题,请告诉我

      【讨论】:

      • 您可能无法提前知道将遇到的数叠。你也永远不会改变你的数组索引。
      猜你喜欢
      • 2011-01-04
      • 1970-01-01
      • 2015-09-15
      • 2012-06-26
      • 2020-12-23
      • 1970-01-01
      • 2017-03-21
      • 2017-08-18
      • 2011-01-29
      相关资源
      最近更新 更多