|
@@ -0,0 +1,78 @@
|
|
1
|
+/**
|
|
2
|
+ * TicketMachine models a naive ticket machine that issues
|
|
3
|
+ * flat-fare tickets.
|
|
4
|
+ * The price of a ticket is specified via the constructor.
|
|
5
|
+ * It is a naive machine in the sense that it trusts its users
|
|
6
|
+ * to insert enough money before trying to print a ticket.
|
|
7
|
+ * It also assumes that users enter sensible amounts.
|
|
8
|
+ *
|
|
9
|
+ * @author David J. Barnes and Michael Kolling
|
|
10
|
+ * @version 2008.03.30
|
|
11
|
+ */
|
|
12
|
+public class TicketMachine
|
|
13
|
+{
|
|
14
|
+ // The price of a ticket from this machine.
|
|
15
|
+ private int price;
|
|
16
|
+ // The amount of money entered by a customer so far.
|
|
17
|
+ private int balance;
|
|
18
|
+ // The total amount of money collected by this machine.
|
|
19
|
+ private int total;
|
|
20
|
+
|
|
21
|
+ /**
|
|
22
|
+ * Create a machine that issues tickets of the given price.
|
|
23
|
+ * Note that the price must be greater than zero, and there
|
|
24
|
+ * are no checks to ensure this.
|
|
25
|
+ */
|
|
26
|
+ public TicketMachine(int ticketCost)
|
|
27
|
+ {
|
|
28
|
+ price = ticketCost;
|
|
29
|
+ balance = 0;
|
|
30
|
+ total = 0;
|
|
31
|
+ }
|
|
32
|
+
|
|
33
|
+ /**
|
|
34
|
+ * Return the price of a ticket.
|
|
35
|
+ */
|
|
36
|
+ public int getPrice()
|
|
37
|
+ {
|
|
38
|
+ return price;
|
|
39
|
+ }
|
|
40
|
+
|
|
41
|
+ /**
|
|
42
|
+ * Return the amount of money already inserted for the
|
|
43
|
+ * next ticket.
|
|
44
|
+ */
|
|
45
|
+ public int getBalance()
|
|
46
|
+ {
|
|
47
|
+ return balance;
|
|
48
|
+ }
|
|
49
|
+
|
|
50
|
+ /**
|
|
51
|
+ * Receive an amount of money in cents from a customer.
|
|
52
|
+ */
|
|
53
|
+ public void insertMoney(int amount)
|
|
54
|
+ {
|
|
55
|
+ balance = balance + amount;
|
|
56
|
+ }
|
|
57
|
+
|
|
58
|
+ /**
|
|
59
|
+ * Print a ticket.
|
|
60
|
+ * Update the total collected and
|
|
61
|
+ * reduce the balance to zero.
|
|
62
|
+ */
|
|
63
|
+ public void printTicket()
|
|
64
|
+ {
|
|
65
|
+ // Simulate the printing of a ticket.
|
|
66
|
+ System.out.println("##################");
|
|
67
|
+ System.out.println("# The BlueJ Line");
|
|
68
|
+ System.out.println("# Ticket");
|
|
69
|
+ System.out.println("# " + price + " cents.");
|
|
70
|
+ System.out.println("##################");
|
|
71
|
+ System.out.println();
|
|
72
|
+
|
|
73
|
+ // Update the total collected with the balance.
|
|
74
|
+ total = total + balance;
|
|
75
|
+ // Clear the balance.
|
|
76
|
+ balance = 0;
|
|
77
|
+ }
|
|
78
|
+}
|