Retrieving a random item from ArrayList [duplicate]
Solution 1:
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;
}
}
Solution 2:
public static Item getRandomChestItem(List<Item> items) {
return items.get(new Random().nextInt(items.size()));
}
Solution 3:
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...