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'
See https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57
Output:
2.857142857142857
2.857142857142857
8.571428571428571
85.71428571428571
a: 2
b: 1
c: 9
d: 88
You must remove the
system.out.println
message from below thereturn
, like this:the
return
statement basically says the function will now end. anything included beyond thereturn
statement that is also in scope of it will result in the behavior you experiencedanyItem has never been declared as a variable, so it makes sense that it causes an error. But more importantly, you have code after a return statement and this will cause an unreachable code error.
Here you go, using
Generics
:As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.