如何解决此随机游走程序代码?

问题描述 投票:0回答:1

我正在创建一个生成随机游走的程序。我不明白为什么以下代码无法正常工作。

当我运行它时,在询问“请输入起始街道整数:”之后,该程序将无法继续进行]

我尝试在Drunkard类中导入Random方法,然后在step方法中使用random方法。我不知道哪一部分错了。

import java.util.Random;

public class Drunkard{
private int x;
private int y;
private int inix;
private int iniy;

public Drunkard(int avenue, int street){
    this.x = avenue;
    this.y = street; 
    this.inix = avenue;
    this.iniy = street;
}

public void fastForward(int howMany){
    int i = 0;
    while (i<howMany){
        step();
    }

}
public void step(){
    Random random = new Random();
    int ranNum = random.nextInt(4);
    if (ranNum == 0){
        this.x +=1;
    } else if (ranNum == 1){
        this.x -=1;  
    } else if (ranNum == 2){
        this.y +=1;  
    } else if (ranNum == 3){
        this.y -=1;   
    }

}
public String getLocation(){
    return x + "avenue " + y + "street";
}
public int howFar(){
    return this.x+this.y-this.inix-this.iniy;
}


}



import java.util.Scanner;

public class DrunkardTester {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Please enter the starting avenue integer: ");
int avenue = input.nextInt();
System.out.println("Please enter the starting street integer: ");
int street = input.nextInt();

// make the Drunkard with initial position
Drunkard ozzy = new Drunkard(avenue,street);

// have him move 100 intersections
ozzy.fastForward(100);

// get his current location
String location = ozzy.getLocation();

// get distance from start
int distance = ozzy.howFar();

System.out.println("Current location: " + location);
System.out.println("That's " + distance + " blocks from start.");

}
}

我正在创建一个生成随机游走的程序。我不明白为什么下面的代码不起作用。当我运行它时,在询问“请输入开始的位置...

java random
1个回答
0
投票

您的代码中存在一个inf循环:

© www.soinside.com 2019 - 2024. All rights reserved.