the second Objects lab.

TicketMachine.java 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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(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. { if (amount >=0){
  52. balance = balance + amount;
  53. } else { System.out.println("You need to add a value greater than 0");
  54. }}
  55. /**
  56. * Print a ticket.
  57. * Update the total collected and
  58. * reduce the balance to zero.
  59. */
  60. public void printTicket()
  61. {
  62. // Simulate the printing of a ticket.
  63. System.out.println("##################");
  64. System.out.println("# The BlueJ Line");
  65. System.out.println("# Ticket");
  66. System.out.println("# " + price + " cents.");
  67. System.out.println("##################");
  68. System.out.println();
  69. // Update the total collected with the balance.
  70. total = total + balance;
  71. // Clear the balance.
  72. balance = 0;
  73. }
  74. }