Results 1 to 5 of 5
Thread: How to add
- 11-02-2012, 11:27 AM #1
Member
- Join Date
- Nov 2012
- Location
- Australia
- Posts
- 4
- Rep Power
- 0
How to add
My add_item method which gets item details, creates item with a custom constructor then adds it to my array list
This is also in my class User which has method that executes on menu select. This method creates a drop down list and asks the user to select an item(element) to remove. However I am unable to get all the item names to display and I want the amount of Indexes to be based on how many items the user adds.Java Code:public ArrayList<Item_props> add_item(ArrayList<Item_props> items) { Messages mesg = new Messages(); String name = mesg.name();//ask for item price double price = mesg.price();//prompt for price int id = (int)(Math.random() * 50);//produce item id int quant = mesg.quantity(); items.add(new Item_props(name, id, price,quant));//create item, store in arrayList return items; }
What can I do to acquire all arraylist elements in the remove_item method???Java Code:public ArrayList<Item_props> remove_item(ArrayList<Item_props> item) { Object choice = (String)JOptionPane.showInputDialog(null,"Select an item to remove","Shoppa Menu", JOptionPane.QUESTION_MESSAGE,null,new Object[]{item.get(0).getItem_name()},""); if(item.contains(choice)) item.remove(choice); return item; }Last edited by Fubarable; 11-02-2012 at 01:30 PM.
-
Re: How to add
Moved from Advanced Java forum as there is nothing advanced about this question. Code tags added to aid readability of posted code. Bold markups removed to aid readability.
- 11-09-2012, 05:25 PM #3
Re: How to add
The contains method in the arraylist will look for an instance of the same object, you can't just throw strings at an "Item_props" array and expect it to find anything. Rather, you need to iterate through the list of all Item_props, and look for one who's field contains the choice text. Then you can remove that item.
- 11-21-2012, 12:34 PM #4
Member
- Join Date
- Nov 2012
- Location
- Australia
- Posts
- 4
- Rep Power
- 0
Re: How to add
All good! I made created a string array which sorted the item names of each item object in the arraylist so this:
null,new Object[]{item.get(0).getItem_name()},"");
went to this:
null,ti},""); ti being my array of strings containing my item object names and the item remove works perfect! Thanks for the input!
- 11-21-2012, 02:20 PM #5
Re: How to add
No problem.
For future reference, it can be a lot easier if you use Generics instead of plain Object types. When something is declared as Object, you have to do a lot of casting to work with it's fields and methods.
See this link:
Lesson: Generics (Updated) (The Java™ Tutorials > Learning the Java Language)


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks