jeudi 21 avril 2016

Java Random Walk Program?

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!




Aucun commentaire:

Enregistrer un commentaire