Question

I am attempting to place a randomly chosen object of my ArrayList into a variable in the class constructor.

public WordsToGuess randomWord()
    {
        int index = randomGenerator.nextInt(words.size());
        WordsToGuess chosenWord = words.get(index);
        return chosenWord;
    }

public Model() throws IOException
    {
        words = new ArrayList<WordsToGuess>();
        chosenWord = words.randomWord();
        randomGenerator = new Random();
        }

I get an error saying "The method randomWord() is undefined for the type ArrayList". I have removed unnecessary code from the constructor.

Was it helpful?

Solution

chosenWord = words.randomWord();

Should read:

chosenWord = randomWord();

randomWord() is not a method of ArrayList but of your class.

OTHER TIPS

Your randomWord() method seems to be a local instance method. Try this instead:

chosenWord = randomWord();

I will add that your design might need some tidying up. It seems your methods have a muddled purpose: Try to keep each method's task as small and focused as possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top