java - 使用循环和随机生成器的程序(java 入门)

标签 java loops random

一个醉汉在街道网格中随机选择四个方向之一并跌跌撞撞地到达下一个十字路口,然后再次随机选择四个方向之一,依此类推。你可能认为酒鬼平均不会走多远,因为选择相互抵消,但事实并非如此。将位置表示为整数对 (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/

相关文章:

java - 在 primefaces DataTable 中显示 Hashmap 键和值

math - 生成排序的随机整数而不进行排序?在)

c++ - 小随机数生成程序?

java - 随机字符和随机颜色生成器

arrays - 在 gnuplot 中循环遍历数组

java - 没有实现接口(interface)的所有方法。可能吗?

java - 无法使用 Spring Boot 自动配置访问 REST Controller

java - 在 Apache Camel 中使用 session 和 Cookie

java - Java 增强 for 循环中的隐式语句

java - 在 while 循环中将对象添加到列表