gpt4 book ai didi

java - 如何修复这个随机行走程序代码?

转载 作者:行者123 更新时间:2023-12-02 00:04:51 25 4
gpt4 key购买 nike

我正在创建一个生成随机行走的程序。我不明白为什么下面的代码不起作用。

当我运行它时,程序在询问“请输入起始街道整数:”后没有继续进行

我尝试在 Drunkard 类中导入 Random 方法,然后在步骤方法中使用 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.");

}
}

最佳答案

您的代码中有一个 inf-loop:

public void fastForward(int howMany){
int i = 0; //this i is never changed
while (i<howMany){
step();
//add here: i++;
}

}

因此它卡在那里,看起来什么也没做。

关于java - 如何修复这个随机行走程序代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58161218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com