我正在创建一个生成随机游走的程序。我不明白为什么下面的代码不起作用。
当我运行它时,在询问“请输入起始街道整数:”后,程序不会继续运行
我尝试在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.");
}
}
答案 0 :(得分:0)
您的代码中存在一个inf循环:
public void fastForward(int howMany){
int i = 0; //this i is never changed
while (i<howMany){
step();
//add here: i++;
}
}
因此它挂在那里,似乎什么也没做。