Zgbrell Zgbrell - 2 months ago 9
Java Question

Pulling a single random String from an Array in Java

To begin, I am a very beginner in Java. I have looked at many different posts regarding similar problems but still could not seem to solve my problem.

String[] names = {"elephant, tiger, monkey, baboon, barbeque, giraffe, simple, zebra, porcupine, aardvark"};
Random rand = new Random();
name = names[rand.nextInt(names.length)];
return name;


From this snippet of code I am trying to have Java select a single word from the string array, such as just selecting the word "Tiger". This is for a Hangman game and this is trying to select the word that the user is trying to solve. Yes, this is for a school assignment so teaching and not just giving code would be GREATLY appreciated.

The main problem I am running into is that when the code is going to grab the word that I want to use, it is selecting the entire String array and is trying to have the user solve the entire thing, when I just want one word from it.

If more code is needed I can supply it, just remember I am a very very beginner in programming so the code is not very good.

Answer

The problem is how you are initializing your string array:

String[] names = {"elephant, tiger, monkey, baboon, barbeque, giraffe, simple, zebra, porcupine, aardvark"}

This is a string array with one string that is "elephant, tiger,...

You want to do this:

String[] names = {"elephant", "tiger", "monkey"...

Notice the extra quotation marks.

Comments