Java随机漫步计划?

时间:2016-04-22 01:39:34

标签: java random

我正在尝试编写一个程序,从中心点(0,0)随机游走100次并计算平均步数。我有以下代码:

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;
   }
}

我也有测试功能:

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

我在这里做错了什么?我的程序似乎总是无限运行,我从来没有得到返回值。它只是继续运行。感谢帮助!

1 个答案:

答案 0 :(得分:1)

当x不为0或y不为0时循环。由于通过随机生成,您无法保证返回0,程序可以永久运行。您可能希望尝试通过步行者采取的步数限制您的循环。

while (steps < 100)

而不是

while (this.x != 0 || this.y != 0)