/** * TicketMachine models a naive ticket machine that issues * flat-fare tickets. * The price of a ticket is specified via the constructor. * It is a naive machine in the sense that it trusts its users * to insert enough money before trying to print a ticket. * It also assumes that users enter sensible amounts. * * @author David J. Barnes and Michael Kolling * @version 2008.03.30 */ public class TicketMachine { // The price of a ticket from this machine. private int price; // The amount of money entered by a customer so far. private int balance; // The total amount of money collected by this machine. private int total; /** * Create a machine that issues tickets of the given price. * Note that the price must be greater than zero, and there * are no checks to ensure this. */ public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; } /** * Return the price of a ticket. */ public int getPrice() { return price; } /** * set the price */ public void setPrice(int ticketCost){ price = ticketCost; } /** * Return the amount of money already inserted for the * next ticket. */ public int getBalance() { return balance; } /** * return the total */ public int getTotal(){ return total; } /** * reduce the price by amount */ public void discount(int amount){ price -= amount; } /** * Receive an amount of money in cents from a customer. */ public void insertMoney(int amount) { if (amount > 0){ balance = balance + amount; } else{ System.out.println("Enter a positive amount: " + amount); } } /** * refund the balance */ public int refundBalance(){ int amountToReturn = balance; balance = 0; return amountToReturn; } /** * print a prompt */ public void prompt(){ System.out.println("Please insert the correct amount of money"); } /** * show the price of the ticket */ public void showPrice(){ System.out.println("The price of the ticket " + price + " cents"); } /** * Print a ticket. * Update the total collected and * reduce the balance to zero. */ public void printTicket() { int amountLeftToPay = price - balance; if (balance >= price){ // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the balance. total = total + price; // Clear the balance. balance = balance - price; } else{ System.out.println("You must enter atleast: " + (amountLeftToPay) + " cents"); } } /** * emptying machine */ public int emptyMachine(){ int moneyInMachine = total; total = 0; return moneyInMachine; } }