2

I need to be able to add words to my Hangman game so my previous arrays was created like this:

Random random = new Random();
String[] word = {"iran","japan","canada","america","malaysia"};
randomword = word[random.nextInt(word.length)];

The problem is that this array is fixed size, so I tried using ArrayList:

ArrayList<String> word = new ArrayList<String>();
word.add("iran");
word.add("japan");
word.add("canada");
Random random = new Random();
randomword = word[random.nextInt(word.length)];

but it didn't work, the error is (array required, but arrayList found)

0

2 Answers 2

3

randomword = word[random.nextInt(word.length)]; there is no syntax in java that allows you to use index with ArrayList , use get() instead.

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

Comments

2

Elements is an ArrayList are retrieved using the get(index) method, and the size() method is used instead of length.

change

randomword = word[random.nextInt(word.length)];

to

randomword = word.get(random.nextInt(word.size()));

1 Comment

Thanks that was quick :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.