• Post Reply Bookmark Topic Watch Topic
  • New Topic

Loaded ArrayList but can't retrieve stored values  RSS feed

 
Larissa Perkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am creating a shopping list, with each element and object called product from the Item attribute class. Each product object has a description, price, and priority. From user input, I am able to create each product object, and then .add to my arraylist. I know that it successfully adds because I have it printed in each iteration of the do-while loop. Once the user indicates they want to quit, the loop ends. I then want to print each description, price, and quantity but this for loop will only print the last element over and over.

Here is what I have:



I know that there is a bug in the code above, that isn't related to my question (description can not be inputted after the first iteration of the do-while). My original code is fine except for the arraylist problem. I took things out so that way it is easier to read.

Please help, and go easy with the terminology. This is only my 7th week into writing Java code.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Three problems that I can see:

1. You ever only create one instance of ItemAttribute (Line 3). Your code now will add the same object over and over again. Since all elements of your arraylist point to that one object, it will look like you're printing the same object over and over again because you essentially are. You need to create a new instance for every ItemAttribute you want to add to your list.

2. You are using == to compare Strings. You shouldn't do that. Use equals() instead: if ("quit".equals(tempDescr))

3. Same problem with the while condition. Don't use != to compare Strings. Use (!"quit".equals(tempDescr)) instead


 
Larissa Perkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you soooo much Junilu! It worked.

I actually left product outside of the loop because I thought that it would over-write after each iteration. I was incorrectly thinking I was saving memory and that product would copy itself into the ArrayList and product could then be over-written. It makes much more sense now.

Thank you again!

P.S. I need to keep working on my .equals on Strings. Thanks for that too!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!