/** * TicketMachine models a ticket machine that issues * flat-fare tickets. * The price of a ticket is specified via the constructor. * Instances will check to ensure that a user only enters * sensible amounts of money, and will only print a ticket * if enough money has been input. * * @author David J. Barnes and Michael Koelling, RCO CITS1001 lab answers * @version 2011.07.31 2017.03.16 */ 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 cost) { price = cost; balance = 0; total = 0; } /** * Return the price of a ticket. */ public int getPrice() { return price; } /** * Return the amount of money already inserted for the * next ticket. */ public int getBalance() { return balance; } /** * Return the total amount of money collected by this machine * Note this does not include the current balance since that is not ours yet * but you could interpret the total as total+balance. But the returned value may not match the field value. */ public int getTotal() { return total; } /** * Receive an amount of money from a customer. * Check amount is reasonable */ public void insertMoney(int amount) { if (amount>0) { balance = balance + amount; } } /** * Print a ticket. * Update the total collected and * reduce the balance to zero. * a) print a ticket only if enough money has been input, * b) print an error message if there is not enough money, * c) deduct only the ticket price from the balance * (possibly leaving change to be given) rather than setting the balance to 0. */ public void printTicket() { 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 price of the ticket total = total + price; // Reduce the balance by the price of the ticket balance = balance - price; } else { System.out.println("Please insert more money to cover ticket price of " + price + " cents"); } } /** * Set the price of this machine's tickets to be cost (if reasonable) */ public void setPrice(int cost) { if (price > 0) { price = cost; } } }