Question
I want to fill an Arraylist from a .txt file however, the ArrayList contains objects (items) with multiple 'variables'. The class Item 'variables' are String
I want to fill an Arraylist from a .txt file however, the ArrayList contains objects (items) with multiple 'variables'.
The class Item 'variables' are String & boolean.
public Item(String aName, String aDescription, boolean canTake) {
This is what I have in a different class to fill the ArrayList
public List- loadItems() throws FileNotFoundException{ File f = new File("Item.txt"); Scanner sn = new Scanner(f); while (sn.hasNext()){ String itm = sn.nextLine(); Scanner sc = new Scanner(itm); sc.useDelimiter("#"); String aName = sc.next(); String aDescription=sc.next(); Boolean canTake = sc.nextBoolean(); addItem(aName, aDescription, canTake); } return items; }
In a third class I have another ArrayList and call the loadItems() method so that I can reference specific item objects (i.e. item objects at element 0 of the list).
public Actions() throws FileNotFoundException { loadItems(); this.itemSlist = loadItems(); ItemList HomeList = new ItemList(); HomeList.add(itemSlist.get(0)); HomeList.add(itemSlist.get(1));
The problem is this doesn't actually fill the ArrayList & my output is: \[\] \[\] \[\] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 0
I know with ArrayLists you would generally just list.add(); but there a multiple variables for each object - not just a string or boolean value.I've tried moving the loadItems method to different classes and tried using a basic scanner with the txtfile and can access single word item objects but not the multi variable one. I cannot just hard code as per the assignment
Step by Step Solution
3.54 Rating (158 Votes )
There are 3 Steps involved in it
Step: 1
1 Modify the loadItems method to properly create and add Item objects ...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started