/** * 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 */ 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; // The total number of tickets sold. private int sold; public void prompt() { System.out.println("Please insert money for ticket."); System.out.println(); } public void showPrice() { System.out.println("The price of a ticket is " + price + " cents."); System.out.println(); } /** * 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() { price = 1000; 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 getAmount() { return balance; } public int getTotal() { return total; } /** * Receive an amount of money in cents from a customer. */ public void insertMoney(int amount) { balance = balance + amount; } /** * Print a ticket. * Update the total collected and * reduce the balance to zero. */ public void printTicket() { // Simulate the printing of a ticket. if (balance == price) { System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); balance = 0; } else if (balance < price) { System.out.println("Not enough money inserted. Please insert " + (price - balance) + " more cents."); System.out.println(); } else if (balance > price) { System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); System.out.println((balance - price) + " cents change returned."); System.out.println(); balance = 0; } // Update the total collected with the balance. total = (total + balance) - (balance - price); } public int ticketsSold() { // Calculates how many tickets have been sold. sold = total / price; return sold; } public void emptyMachine() { total = 0; } public void setPrice(int newPrice) { price = newPrice; } public void refeundBalance() { int amountToRefund; amountToRefund = balance; System.out.println(amountToRefund + " cents refunded."); System.out.println(); } }