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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /**
  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. /**
  32. * Return the price of a ticket.
  33. */
  34. public int getPrice()
  35. {
  36. return price;
  37. }
  38. /**
  39. * Return the amount of money already inserted for the
  40. * next ticket.
  41. */
  42. public int getBalance()
  43. {
  44. return balance;
  45. }
  46. /**
  47. * Receive an amount of money in cents from a customer.
  48. */
  49. public void insertMoney(int amount)
  50. {
  51. balance = balance + amount;
  52. }
  53. /**
  54. * Print a ticket.
  55. * Update the total collected and
  56. * reduce the balance to zero.
  57. */
  58. public void printTicket()
  59. {
  60. // Simulate the printing of a ticket.
  61. System.out.println("##################");
  62. System.out.println("# The BlueJ Line");
  63. System.out.println("# Ticket");
  64. System.out.println("# " + price + " cents.");
  65. System.out.println("##################");
  66. System.out.println();
  67. // Update the total collected with the balance.
  68. total = total + balance;
  69. // Clear the balance.
  70. balance = 0;
  71. }
  72. }