I have been running a program that simulates the number of steps it will take to get across a 7-step bridge. A random number is generated to determine if the person takes a step forwards or backwards. This simulation is run 1000 times. After this the average number of steps it takes to get across is out printed, as well as the maximum number of steps it took.
This, in turn is run 1000 times. It compiles fine. My issue is that when I go to run it, (on BlueJ) the bar shows that it is running but the output window fails to appear. What is happening? (Most likely is something stupidly obvious that I am oblivious to.)
import java.util.Random;
public class Prog214a
{
public static void main (String[] args)
{
Random rn = new Random();
for (int m = 1; m <= 20; m++)
{
int max = 0;
for (int c = 1; c <= 1000; c++)
{
int s = 0;
int sn = 0;
int sum = 0;
while (s < 7)
{
int ans = rn.nextInt(1) + 0;
if (ans == 1) {
s = s + 1
}
else {
s = s - 1;
}
sn++;
}
sum = sum + sn;
if (sn > max) {
max = sn;
}
if (c == 1000) {
double avg = sum / c;
System.out.print(avg);
System.out.print(" " + max);
}
}
}
}
}
There is at least one problem. Here:
int ans = rn.nextInt(1) + 0;
if (ans == 1){
s = s + 1;
}
else {
s = s -1;
}
rn.nextInt(1)
can only return 0, so ans
will be 0. You have no guard to ensure that s
does not go negative, so it does - and it remains less than 7, meaning that the while loop (with condition s < 7
) goes on for a long time (specifically, until s
wraps back to a positive number again).