Zgbrell
Zgbrell

Reputation: 159

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.

Upvotes: 0

Views: 134

Answers (3)

Jaken
Jaken

Reputation: 1343

Your array as of right now is one long string. If you were to call names[0], you would get elephant, tiger, monkey, baboon, barbeque, giraffe, simple, zebra, porcupine, aardvark back.

You need to initialize your array with individual strings such as elephant, tiger, monkey, etc.

Upvotes: -1

vardhan
vardhan

Reputation: 21

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

Use this, hope you understood why. You have assigned the whole thing as a single element before.

Upvotes: 2

Simba
Simba

Reputation: 1651

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.

Upvotes: 3

Related Questions