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

TicketMachine.java 2.2KB

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