Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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 ... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

C++ Primer Plus

Authors: Stephen Prata

6th Edition

978-0321776402, 0321776402

More Books

Students also viewed these Operating System questions

Question

4 How do you see the future of integrative approaches to coaching?

Answered: 1 week ago