Java:随机生成的零的数量

时间:2016-10-26 15:38:33

标签: java if-statement while-loop count whitespace

我无法弄清楚如何让Java计算随机生成的数字列表中的零数量,直到达到“-10”或“+10”为止。

我很感激任何帮助,

谢谢。

我的代码:

import java.util.Random;

public class RandomWalk 
{
    public static void main(String[] args) 
    {
        Random rand = new Random();

        int position = 0;
        int stepsTotal = 0;
        int zeroesTotal = 0;

         while (position !=10 && position != -10) {
             if (rand.nextDouble() < 0.5) {
                 position--; 
             }
             if (rand.nextDouble() < 0.5) {
                 position++; 
             }
             else {
                 zeroesTotal++ ; 
             }

             stepsTotal++;

             System.out.print(" " + position); 
         }
         System.out.println();
         System.out.println("The final position is: " + position);
         System.out.println("The number of steps taken is: " + stepsTotal);
         System.out.println("There are " + zeroesTotal + " zeroes." );
    }
}

示例输出:(我计算4个零,而不是21个。)(甚至计算什么?)

0 0 0 0 1 1 2 3 4 4 4 3 3 4 4 4 5 6 6 6 6 5 5 6 7 8 7 7 7 6 6 6 6 7 7 7 7 8 8 8 9 8 9 9 8 7 8 9 9 9 10

最终职位是:10

采取的步骤是:58

有21个零。 (错误的地方)

1 个答案:

答案 0 :(得分:3)

如果位置实际位于zeroesTotal,请确保您正在递增0。此外,每次迭代都不需要生成两个随机数。

public static void main(String[] args) 
{
    Random rand = new Random();

    int position = 0;
    int stepsTotal = 0;
    int zeroesTotal = 0;

     while (position != -10 && position != 10) {
         if (rand.nextDouble() < 0.5) {
             position--; 
         }
         else {
             position++; 
         }

         if (position == 0) {
            zeroesTotal++;
         }

         stepsTotal++;

         System.out.print(" " + position); 

     }
     System.out.println();
     System.out.println("The final position is: " + position);
     System.out.println("The number of steps taken is: " + stepsTotal);
     System.out.println("There are " + zeroesTotal + " zeroes." );
}