0

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome thank you! feel kind of silly that I didnt realize that was the issue with it initially. thanks alot!
2
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.

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.