Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

My version of Hangman (In Java)

After finishing the Java Objects course, I decided to take my Hangman game a little further. I thought it's a little boring if you know the word (since you yourself pass in the word), so I added a flavor of randomness.

However... I was also looking for a Java function that can pick a random value out of an array. I couldn't find a function like that, so I did this:

String[] words = {
    "elephant", "giraffe", "kangaroo", "apples", "orange",
    "laptop", "dictionary", "static", "microsecond",
    "leather", "printer", "station", "picture", "computer",
    "community", "tracks", "trains", "support", "organization",
    "members", "private", "increment", "calculator", "headphones",
    "stickers", "mathematics", "structure", "cryptography",
    "watch", "palace", "castle", "lighter", "scratch", "diamond",
    "emerald"
};

Random rand = new Random();

String word = "";
for (String i : words) {
    if (rand.nextBoolean()) {
        word = i;
    }
}

I know that my method of retrieving a random value won't always work, so I'd appreciate any help on getting a random element out of my array of words.

Thanks! That's all I can say.

Again, any help is deeply appreciated :)

~Alex

1 Answer

Hey Alexander,

You can use the nextInt() method in the Random class to generate a random array index that will always be within the bounds of the array. The for each loop is not needed here.

Random rand = new Random();
int randomIndex = rand.nextInt(words.length);
System.out.println(words[randomIndex]);

Thank you very much!

By the way, I've been experimenting of jshell and I found that rand.nextInt() makes a number too big. I didn't know you can pass in a argument!

Thanks again for letting me accomplish my goal.

~Alex