HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Vending Machine class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
machineclassvending

Problem

I am looking for ways to improve the code that I wrote for this.


Consider a simple vending machine class. The machine accepts tokens
and dispenses cans of refreshing beverages. Write a complete class (on
the next page) as described below:



  • The class has two instance data fields; one to keep track of the number of cans in the machine and one to keep track of the number of


tokens (think coins) collected.

  • There should be two constructors. One takes no arguments and starts with 50 cans and zero tokens. The other takes one argument, the


initial number of cans in the machine.

  • There should be a method to purchase a drink which adds one token to the machine and subtracts one can – assuming there are still cans in


the machine to be purchased.

  • There should be one method to add cans to the machine.



  • There should be separate methods to return the number of cans remaining and the number of tokens collected.


Write a toString( ) method to allow for easy printing of a vending machine object


```
public class Vendingmachine
{
private int tokens;
private int cans;

public Vendingmachine()
{
tokens=0;

cans=50;
}

public Vendingmachine( int ca)
{
tokens=0;

cans=ca;

System.out.printf(" The constructor for this %s\n", this);
}
public void setTokens( int coins)
{
tokens = coins;
}

public void setCans ( int ca)
{
cans = ca;
}

public void purchase( int coins)
{
tokens = coins;
if (tokens >=1)
cans = cans-tokens;
if (cans == 0)
addCans();
}

public int getTokens()
{
return tokens;
}

public int getCans()
{
cans = cans- tokens;
return cans;
}

public void addCans()
{

cans =50;
}

public String toString()
{
String str = "You have purchased "+ cans + " cans and have entered the following a

Solution

I've noted a few things you could consider:

  • Your class should probably be VendingMachine, note the capital M.



  • The value 50 is a magic number and should probably be defined as a const at the top of your class.



  • The use of coins and tokens is confusing as they appear to refer to the same thing. Pick one term and use it everywhere.



  • getCans() changes the value of cans. This is a side-effect, which is generally considered a no-no, especially in a getter.



  • The Java idiom for decrementing is -=, so I'd change cans = cans - tokens; to cans -= tokens;



-
Both constructors contain similar code. I'd change the first to use the second, thus:

public Vendingmachine() {
this(50);
}

Context

StackExchange Code Review Q#149254, answer score: 3

Revisions (0)

No revisions yet.