the second Objects lab.

TicketMachine.java 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. 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. private int status;
  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. public void prompt()
  33. {
  34. System.out.println("Please insert the correct amount of money.");
  35. }
  36. public void showPrice()
  37. {
  38. System.out.println("The price of a ticket is " + price + " cents.");
  39. }
  40. /**
  41. * Return the price of a ticket.
  42. */
  43. public int getPrice()
  44. {
  45. return price;
  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. /**
  56. * Receive an amount of money in cents from a customer.
  57. */
  58. public void insertMoney(int amount)
  59. {
  60. balance = balance + amount;
  61. }
  62. public int getTotal()
  63. {
  64. return total;
  65. }
  66. /**
  67. * Print a ticket.
  68. * Update the total collected and
  69. * reduce the balance to zero.
  70. */
  71. public void printTicket()
  72. {
  73. // Simulate the printing of a ticket.
  74. System.out.println("##################");
  75. System.out.println("# The BlueJ Line");
  76. System.out.println("# Ticket");
  77. System.out.println("# " + price + " cents.");
  78. System.out.println("##################");
  79. System.out.println();
  80. // Update the total collected with the balance.
  81. total = total + balance;
  82. // Clear the balance.
  83. balance = 0;
  84. }
  85. }