the second Objects lab.

TicketMachine.java 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 James Seo
  10. * @version 2018.05.24
  11. */
  12. public class TicketMachine {
  13. // The price of a ticket from this machine.
  14. private int price;
  15. // The amount of money entered by a customer so far.
  16. private int balance;
  17. // The total amount of money collected by this machine.
  18. private int total;
  19. /**
  20. * Create a machine that issues tickets of the given price.
  21. * Note that the price must be greater than zero, and there
  22. * are no checks to ensure this.
  23. */
  24. public TicketMachine(int ticketCost) {
  25. price = ticketCost;
  26. balance = 0;
  27. total = 0;
  28. }
  29. /**
  30. * Return the price of a ticket.
  31. */
  32. public int getPrice() {
  33. return price;
  34. }
  35. /**
  36. * Return the amount of money already inserted for the
  37. * next ticket.
  38. */
  39. public int getBalance() {
  40. return balance;
  41. }
  42. /**
  43. * Receive an amount of money in cents from a customer.
  44. */
  45. public void insertMoney(int amount) {
  46. balance = balance + amount;
  47. }
  48. public int getTotal() {
  49. return total;
  50. }
  51. public void getPrompt() {
  52. System.out.println("Please insert the correct amount of money.");
  53. }
  54. public void showPrice(){
  55. System.out.println("# " + price + " cents.");
  56. }
  57. public void setEmpty(){
  58. total = 0;
  59. }
  60. public void setPrice(int newPrice){
  61. price = newPrice;
  62. }
  63. /**
  64. * Print a ticket.
  65. * Update the total collected and
  66. * reduce the balance to zero.
  67. */
  68. public void printTicket()
  69. {
  70. // Simulate the printing of a ticket.
  71. System.out.println("##################");
  72. System.out.println("# The BlueJ Line");
  73. System.out.println("# Ticket");
  74. System.out.println("# " + price + " cents.");
  75. System.out.println("##################");
  76. System.out.println();
  77. // Update the total collected with the balance.
  78. total = total + balance;
  79. // Clear the balance.
  80. balance = 0;
  81. }
  82. }