• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

vending machine code

 
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!

 
Marshal
Posts: 65110
247
  • 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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!