This question already has an answer here:
- Randomly select an item from a list 2 answers
I'm learning Java and I'm having a problem with ArrayList
and RandomGenerator
.
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 item
objects 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;
private ArrayList<Item> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Item>();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
return catalogue.get(index);
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
}
When I try to compile I get an error pointing at the System.out.println
line saying..
'cannot find symbol variable anyItem'
anyItem
is a method and theSystem.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:
try this
And I strongly suggest you to get a book, such as Ivor Horton's Beginning Java 2
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
You havent the variable anyItem initialized or even declared.
This code: + anyItem +
means get value of toString method of Object anyItem
The second thing why this wont work. You have System.out.print after return statement. Program could never reach tha line.
You probably want something like:
}
btw: in Java its convetion to place the curly parenthesis on the same line as the declaration of the function.
Here's a better way of doing things:
The solution is not good, even you fixed your naming and unreachable statement of that print out.
things you should pay attention also 1. randomness seed, and large data, will num of item is so big returned num of that random < itemlist.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
The toString part is just a quickie -- you might want to add a method 'getItemDescription' that returns a useful String for this purpose...