Retrieving a random item from ArrayList

Will picture Will · Feb 17, 2011 · Viewed 236.5k times · Source

I'm learning Java and I'm having a problem with ArrayList and Random.

I have an object called catalogue which has an array list of objects created from another class called item.

I need a method in catalogue which returns all the information on one of the itemobjects in the list.
The item needs to be selected at random.

import java.util.ArrayList;
import java.util.Random;

public class Catalogue
{
    private Random randomGenerator = new Random();
    private ArrayList<Item> catalogue;

    public Catalogue ()
    {
        catalogue = new ArrayList<Item>();  
    }

    public Item anyItem()
    {
        int index = randomGenerator.nextInt(catalogue.size());
        System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
        return catalogue.get(index);
    }

When I try to compile I get an error pointing at the System.out.println line saying..

'cannot find symbol variable anyItem'

Answer

Robby Pond picture Robby Pond · Feb 17, 2011

anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.

Might want to re-write it like:

import java.util.ArrayList;
import java.util.Random;

public class Catalogue
{
    private Random randomGenerator;
    private ArrayList<Item> catalogue;

    public Catalogue()
    { 
        catalogue = new ArrayList<Item>();
        randomGenerator = new Random();
    }

    public Item anyItem()
    {
        int index = randomGenerator.nextInt(catalogue.size());
        Item item = catalogue.get(index);
        System.out.println("Managers choice this week" + item + "our recommendation to you");
        return item;
    }
}