This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Vending Machine Program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Vending Machine Program" Watch "Vending Machine Program" New topic

Vending Machine Program

Alex Morph

Joined: Mar 14, 2013
Posts: 2
Hey first post of the forums, sorry if I break any rules!
Basically I have to create a program that will store values for 'Cans' and 'Tokens'. Simple vending machine like program, where the user inserts 2 tokens and gets 1 can.
I've only been doing java for about 3 weeks, and still trying to get my head around constructors, objects and classes etc. I'm not sure exactly how to go about writing the constructor.
I know it makes an instance of the class, but how should I write this in the code?

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11882

Constructors can be very simple. If you were to create a real live physicial vending machine, what would it's initial state be? How many cans and how many tokens would it have in it?

That's what a constructor should do - set those value to what makes sense for the initial creation.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 44590
Welcome to the Ranch

To continue from what Fred said: you have a number of fields in your class, and the constructor must (well, at least in my opinion) set them all to sensible values. That is called establishing the class invariants.
Your method with the number of cans will almost cretahinly not do what you want it to.
I agree. Here's the link:
subject: Vending Machine Program
It's not a secret anymore!