Paladin-San Paladin-San - 2 months ago 11
Java Question

Printing out multiple random results

I'm making a random creature generator, its going all nice and dandy, however when it comes to printing the results, it prints the same result 5 times. I tried some different things like using println() multiple times and do while loops, however every time I run the file I just get a bunch of the same results. "a b c d e" are strings that generate the creature

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

Answer Source

The reason why you're getting the same answer 5 times is because your do-while loop runs 5 times without changing the 'creatures' .

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

If you remove the do-while loop you'll get the same answer only once however just in case i misunderstood your question i made a small demo of a simple way in which to get multiple random results with a for-loop,a String-array and the Random class

 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);

    }