• Post Reply Bookmark Topic Watch Topic
  • New Topic

OOP total cost always printing out as 0.0  RSS feed

 
Ada Bradburry
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We need to write a program using a given purchase class to calculate the cost of some grocery items and add them up to display the total cost. I get the cost of the item based on the sale just fine, but it always prints out 0.0 as the total cost (except at the end where it prints out 0.00.00.00.00.0) DX Any advice? I'm a novice and having been working on this for hours with no luck

My code:


the class:
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a simple explanation that will, I'm afraid, make you slap your hand to your forehead (or your forehead on your desk, depending on your temperament :-):

Carefully consider what lines 14 and 63 of your Purchase class do.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As to why it prints "0.00.00.00.00.0" at the end, that may be a little tricky for a beginner to understand. So just replace lines 53/54 of your PurchaseResolver class with
System.out.println("Total bill $" + (orange.getTotalCost() + egg.getTotalCost() + apple.getTotalCost() + watermelon.getTotalCost()));
and it should work the way you intended it to.
 
Ada Bradburry
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Dittmer wrote:As to why it prints "0.00.00.00.00.0" at the end, that may be a little tricky for a beginner to understand. So just replace lines 53/54 of your PurchaseResolver class with
System.out.println("Total bill $" + (orange.getTotalCost() + egg.getTotalCost() + apple.getTotalCost() + watermelon.getTotalCost()));
and it should work the way you intended it to.


It doesn't print 0.00.00.00.00.0 at the end, but all of the total cost's still print out as 0.0
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What did you change in your code? What I mentioned in my second post only deals with the printing issue; you still need to consider what I said in my first post - and then change something in your code.
 
Marcel Cristian Dinca
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You first call the method SetTotalCost() and then you call the method ReadInput() witch read the number of items. When you call SetTotalCost(), "numberBought" is 0, that's why the TotalCost is 0.
Not sure If I'm right, couldn't copy/paste the code, and you wrote too many lines of code for what you needed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!