Aramza Aramza - 1 month ago 7
Java Question

Java: Number of Randomly Generated Zeroes

I am having trouble figuring out exactly how to get Java to count the amount of zeroes in the randomly generated list of numbers that goes until it reaches either "-10" or "+10."

I'd appreciate any help,

Thank you.

My Code:

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


Example output: (I count 4 zeroes, not 21.) (What's it even counting?)

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

The final position is: 10

The number of steps taken is: 58

There are 21 zeroes. (Where the error is)

Answer

Make sure you're incrementing zeroesTotal if the position is actually at 0. Also, there's no need to generate two random numbers per iteration of your walk.

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