Results 1 to 3 of 3
- 08-03-2011, 12:45 PM #1
Member
- Join Date
- Aug 2011
- Posts
- 1
- Rep Power
- 0
Problem with Class String Variable
Dear all, I'm writing some code, but I run into this problem
I have this class Inventory and ingredient. Within Inventory, there is an ArrayList of ingredients. I also have a function addIngredient in Inventory that adds an ingredient to the ArrayList. My problem is, after adding several ingredients to the ArrayList, each of the names of the Ingredients are all the same.
But, again, all the ingredient names end up being the last name added, "Peanuts". Am I missing a subtly in passing and setting Strings?Java Code:import java.util.ArrayList; public class Inventory { int numIngred;; ArrayList ingred = new ArrayList<Ingredient>(); public Inventory() { numIngred = 0; } public int getNumIngred() { return numIngred; } public String getIngredientName(int n) { return ((Ingredient)ingred.get(n)).getName(); } public Ingredient getIngredient(int n) { return (Ingredient)ingred.get(n); } public void addIngredient(String iname) { numIngred++; ingred.add(new Ingredient(iname)); } } import java.util.ArrayList; public class Ingredient { public static String name; public Ingredient( String str ) { name = str; } public String getName() { return name; } public void setName(String s) { name = s; } } //In some other class's main: Inventory inven = new Inventory(); inven.addIngredient("Cheese"); inven.addIngredient("Apples"); inven.addIngredient("Carrots"); inven.addIngredient("Peanuts");
Thank you,
Alex
- 08-03-2011, 01:23 PM #2
Sounds like you have one object with many references to it.each of the names of the Ingredients are all the same.
Or you are using static variables.Last edited by Norm; 08-03-2011 at 01:27 PM.
- 08-03-2011, 01:24 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,400
- Blog Entries
- 7
- Rep Power
- 17
Similar Threads
-
super class reference variable accesses overriding sub class method
By subith86 in forum New To JavaReplies: 5Last Post: 01-26-2011, 06:38 PM -
problem regarding giving value to string variable
By enggvijaysingh@gmail.com in forum Advanced JavaReplies: 3Last Post: 12-17-2010, 10:11 PM -
String variable problem
By gkoef in forum New To JavaReplies: 4Last Post: 12-05-2010, 02:15 PM -
accessing a one class's non static variable from another class
By aruna1 in forum New To JavaReplies: 6Last Post: 03-31-2009, 04:27 AM -
I can't seem to pass the value of a string variable into a string array
By mathias in forum Java AppletsReplies: 1Last Post: 08-03-2007, 10:52 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks