打印出多个随机结果

时间:2017-08-19 20:15:15

标签: java

我正在制作一个随机的生物发生器,它会变得漂亮和花花公子,但是当打印结果时,它会打印相同的结果5次。我尝试了一些不同的东西,比如多次使用println()并执行while循环,但是每次运行文件时我都会得到一堆相同的结果。 “a b c d e”是生成该生物的字符串

int x = 1;
do {
  System.out.println(x +" " +a +" " +b +" " +c +" " +d +" " +e);
  x++;
} while (x<=5);

1 个答案:

答案 0 :(得分:0)

你得到相同答案5次的原因是因为你的do-while循环运行了5次而没有改变'生物'。

System.out.println(a +" "+ b + " " + c + " " + d + " " +e);

如果你删除了do-while循环,你只会得到相同的答案一次,但是为了防止我误解了你的问题,我做了一个简单方法的小演示,用for循环得到多个随机结果,一个String数组和Random类

 String[] creatures = {"Dog", "Cat", "Fish", "Monkey", "Horse"};
    Random r = new Random();

    for (int i = 0; i < 5; i++) {
        String creature1 = creatures[r.nextInt(creatures.length)];
        String creature2 = creatures[r.nextInt(creatures.length)];
        String creature3 = creatures[r.nextInt(creatures.length)];
        String creature4 = creatures[r.nextInt(creatures.length)];
        String creature5 = creatures[r.nextInt(creatures.length)];

        System.out.println(creature1 + " " + creature2 + " " + creature3
                + " " + creature4 + " " + creature5);

    }