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 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 = 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'
nextInt() method of Random class can be used to generate a random value between 0 and the size of ArrayList. Now use this number as an index of the ArrayList. Use get () method to return a random element from the ArrayList using number generated from nextInt() method.
Search Operation This is because ArrayList allows random access to the elements in the list as it operates on an index-based data structure while LinkedList does not allow random access as it does not have indexes to access elements directly, it has to traverse the list to retrieve or access an element from the list.
ArrayList clone() method is used to create a shallow copy of the list.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With