一个醉汉在街道网格中随机选择四个方向之一并跌跌撞撞地到达下一个十字路口,然后再次随机选择四个方向之一,依此类推。你可能认为酒鬼平均不会走多远,因为选择相互抵消,但事实并非如此。将位置表示为整数对 (x,y)。实现醉汉步行超过 100 个十字路口,从 (0,0) 开始并打印结束位置
有人可以帮忙吗?我完全迷失在同一个程序中使用随机生成器和循环
以下是我所拥有的。它符合要求,但不打印任何内容,我不确定随机 100 个交叉点是否正确
import java.util.*;
class Drunkard {
int x, y;
Drunkard(int x, int y) {
this.x = x;
this.y = y;
}
void moveNorth() {
this.y -= 1;
}
void moveEast() {
this.x += 1;
}
void report() {
System.out.println("Hiccup: " + x + ", " + y);
}
}
class Four {
public static void main(String[] args) {
Random generator = new Random();
Drunkard drunkard = new Drunkard(100, 100);
int direction;
for (int i = 0; i < 100; i++) {
direction = Math.abs(generator.nextInt()) % 4;
if (direction == 0) { // N
drunkard.moveNorth();
} else if (direction == 1) { // E
drunkard.moveEast();
} else if (direction == 2) { // S
System.out.println("Should move South.");
} else if (direction == 3) { // W
System.out.println("Should move West.");
} else {
System.out.println("Impossible!");
}
System.out.drunkard.report();
}
}
}
最佳答案
您的程序将是:
initialization
loop: for 1 to 100, do:
i = random() if i<=0.25 : go north if i>0.25 and i<=0.5 : go south if i>0.5 and i<= 0.75 : go east if i>0.75 and i<= 1 : go west
end loop
show final point.
关于java - 使用循环和随机生成器的程序(java 入门),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19819984/