the second Objects lab.

TicketMachine.java 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. * Create a machine that issues tickets of the given price.
  22. * Note that the price must be greater than zero, and there
  23. * are no checks to ensure this.
  24. */
  25. public TicketMachine(int ticketCost)
  26. {
  27. price = ticketCost;
  28. balance = 0;
  29. total = 0;
  30. }
  31. public TicketMachine()
  32. {
  33. price = 700;
  34. balance = 0;
  35. total = 0;
  36. }
  37. /**
  38. * Return the price of a ticket.
  39. */
  40. public int getPrice()
  41. {
  42. return price;
  43. }
  44. public void setPrice(int newPrice) {
  45. price = newPrice;
  46. }
  47. /**
  48. * Return the amount of money already inserted for the
  49. * next ticket.
  50. */
  51. public int getBalance()
  52. {
  53. return balance;
  54. }
  55. public void prompt() {
  56. System.out.println("Please insert the correct amount of money");
  57. }
  58. public void showPrice() {
  59. System.out.println("The price of a ticket is " + price + " cents.");
  60. }
  61. /**
  62. * Receive an amount of money in cents from a customer.
  63. */
  64. public void insertMoney(int amount)
  65. {
  66. balance = balance + amount;
  67. }
  68. public void empty() {
  69. total = 0;
  70. }
  71. /**
  72. * Print a ticket.
  73. * Update the total collected and
  74. * reduce the balance to zero.
  75. */
  76. public void printTicket()
  77. {
  78. // Simulate the printing of a ticket.
  79. System.out.println("##################");
  80. System.out.println("# The BlueJ Line");
  81. System.out.println("# Ticket");
  82. System.out.println("# " + price + " cents.");
  83. System.out.println("##################");
  84. System.out.println();
  85. // Update the total collected with the balance.
  86. total = total + balance;
  87. // Clear the balance.
  88. balance = 0;
  89. }
  90. }