Java:随机生成的零数

Java: Number of Randomly Generated Zeroes

我无法弄清楚如何 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 3 4 3 4 4 5 5 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个零。 (错误所在)

如果位置实际在 0,请确保递增 zeroesTotal。此外,无需在每次步行迭代中生成两个随机数。

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