• Post Reply Bookmark Topic Watch Topic
  • New Topic

vending machine code  RSS feed

 
Leyli Majnun
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to fix some logic errors in my vending machine code, but by this point I'm completely confused. The process should go from money deposit to item selection, and then to change in coins (if any). I'm also not sure what to code to refund the initial amount/money deposited. Thanks!

 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I suggest you change the multiple print statements to this:-
And always use %n rather than \n. The reason which you won't notice now, but will notice when you have thousands of print statements, is that the print statements take a few milliseconds to execute, so you might as well reduce it to one statement. The compiler will sort out all the + operators for you so there will be no delay in executing them. And why are you using Strings for the prices rather than numbers?

If you use floating‑point arithmetic and then try comparisons with == and !=, you are going to run into trouble. Try this loop and guess how many times it runs:-That's right. It runs 11 times. That is because floating point arithmetic is always implicitly imprecise. We have an FAQ (No 20) about that. If you have != 0 somewhere, that may always be true and your loop might run for ever (or as least 2⁶⁴×).

There are at least two alternatives to floating‑point arithmetic. Read this thread and this one to find out about the BigDecimal class.
Rather than putting dollars in, put in ¢ and do all your arithmetic with ints.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!