Reputation: 1065
I am trying to write a program that takes a random walk from a center point (0,0) 100 times and calculates the average number of steps taken. I have the following code:
package randomwalk;
import java.util.Random;
public class RandomWalk {
int x = 0;
int y = 0;
int steps = 0;
Random r = new Random();
public RandomWalk(){
do {
int num = randInt(1,4);
if(num == 1){
this.x+=1;
}
else if(num == 2){
this.x-=1;
}
else if(num == 3){
this.y+=1;
}
else if(num == 4){
this.y-=1;
}
this.steps++;
} while(this.x != 0 || this.y != 0);
}
public int getSteps(){
return this.steps;
}
public static int randInt(int min, int max){
Random r = new Random();
int num = r.nextInt((max-min) + 1) + min;
return num;
}
}
I also have the test function:
package randomwalk;
public class Test {
public static void main(String args[]){
int total = 0;
for(int i = 0; i<100; i++){
RandomWalk rand = new RandomWalk();
int steps = rand.getSteps();
total+=steps;
}
System.out.println("The average is: " + ((total/2) / 100));
}
}
What am I doing wrong here? My program seems to always run infinitely and I never get a return value. It just keeps running. Help is appreciated!
Upvotes: 0
Views: 10086
Reputation: 6780
You loop while x is not 0 or y is not 0. Since by random generation you are not guaranteed to ever get back to 0, the program can run forever. You might want to try limiting your loop by the number of steps a walker takes.
while (steps < 100)
instead of
while (this.x != 0 || this.y != 0)
Upvotes: 1