Chapter 2 of the BlueJ book. Walk through many of the chapters exercises.

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