import java.util.*;
public class Vendingmachine {
public static int colaAvailable = 2;
public static int mineralWaterAvailable = 1;
public static int lemonadeAvailable = 3;
public static int canPrice = 25;
public static void main(String[] args) {
// if there are any cans left in the vending machine, it will continue. If the method cansAvailable validates to true, the program will continue.
while (cansAvailable())
choosedrink();
// else it calls the method outoforder and shuts down
outoforder();
}
public static void choosedrink() {
//loading scanner to get the user input
System.out.println("Welcome to the vending machine.");
System.out.println("Select one of the following drinks;");
if(colaAvailable > 0)
System.out.println("1 - Cola");
if(mineralWaterAvailable > 0)
System.out.println("2 - Mineral water");
if(lemonadeAvailable > 0)
System.out.println("3 - Lemonade");
Scanner console = new Scanner(System.in);
int selection = console.nextInt();
System.out.println("Now insert 25 Rupiah");
int coininput, totalAmount = canPrice;
coininput = console.nextInt();
totalAmount = totalAmount-coininput;
while ( totalAmount > 0) { // continues payment, until exact amount or too much is payed, in which case the machine returns the change
if (totalAmount > 0) { // not enough money input, put more in
System.out.println("Please insert " + totalAmount + " Rupiah");
coininput = console.nextInt();
totalAmount = totalAmount-coininput;
}
if (totalAmount < 0) { // too much money put in, change back
System.out.println("Thank you. Here is your change; " + -totalAmount+ " Rupiah");
totalAmount = totalAmount-coininput;
}
}
//launches the subsraction method, so the machine "knows" that there are on less can in the machine
cansubstraction(selection);
//when totalAmount is not less or larger than 0, it must be = 0, and then this print comes
System.out.println("Thank you, here is your can."); // perfect amount of money input, merchandise is given
System.out.println();
}
public static boolean cansAvailable () {
// this metod checks if there is any cans left. if just one of these 3 variables validates to true (over 0 left)
//then it returns the true statement and the program will run
if(colaAvailable > 0 || mineralWaterAvailable > 0 || lemonadeAvailable > 0)
return true;
// if it's not true, of course then it returns false and the programs activates the method that forces the machine to stop
return false;
}
public static void cansubstraction (int selection) {
// if either, 1,2 or 3 was selected, this method substracts one from that selection.
if(selection == 1)
colaAvailable--;
else if(selection == 2)
mineralWaterAvailable--;
else if(selection == 3)
lemonadeAvailable--;
}
// gives the following message, if there are no cans left in the machine
public static void outoforder() {
System.out.println("The machine is temporarily out of order");
}
}