This method randomly increments or decrements (with equal probability) until either -3 or 3 are reached. I'd like to maintain printing the value of pos
on each iteration, and printing the largest positive number max
reached at the end of the loop. How can I improve this method using the Random()
function? I know this sounds pretty ambiguous, but I'd like to know if I can make rand.nextInt(2) == 0
an easier condition to understand? Any suggestions/improvements are welcome!
public static void randomWalk() {
Random rand = new Random();
int pos = 0;
int max = 0;
System.out.println("position = " + pos);
while (pos > -3 && pos < 3) {
if (rand.nextInt(2) == 0) {
pos++;
if (pos > 0) {
max = pos;
}
} else {
pos--;
}
System.out.println("position = " + (int) pos);
}
System.out.println("max position = " + max);
}