Retrieving a random item from ArrayList
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;
}
}
public static Item getRandomChestItem(List<Item> items) {
return items.get(new Random().nextInt(items.size()));
}
your print comes after you return -- you can never reach that statement. Also, you never declared anyItem to be a variable. You might want
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item randomItem = catalogue.get(index);
System.out.println("Managers choice this week" + randomItem.toString() + "our recommendation to you");
return randomItem;
}
The toString part is just a quickie -- you might want to add a method 'getItemDescription' that returns a useful String for this purpose...
Here you go, using Generics
:
private <T> T getRandomItem(List<T> list)
{
Random random = new Random();
int listSize = list.size();
int randomIndex = random.nextInt(listSize);
return list.get(randomIndex);
}