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

TicketMachine.java 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. //hello Zipcode
  13. public 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. /**
  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. /**
  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. }