Java Reference
In-Depth Information
Code 2.8
continued
A more sophisticated
TicketMachine
/**
* Receive an amount of money in cents from a customer.
* Check that the amount is sensible.
*/
public
void
insertMoney(
int
amount)
{
if
(amount > 0) {
balance = balance + amount;
}
else
{
System.out.println(
"Use a positive amount rather than: "
+
amount);
}
}
/**
* Print a ticket if enough money has been inserted, and
* reduce the current balance by the ticket price. Print
* an error message if more money is required.
*/
public
void
printTicket()
{
if
(balance >= price) {
// Simulate the printing of a ticket.
System.out.println(
"##################"
);
System.out.println(
"# The BlueJ Line"
);
System.out.println(
"# Ticket"
);
System.out.println(
"# "
+ price +
" cents."
);
System.out.println(
"##################"
);
System.out.println();
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
}
else
{
System.out.println(
"You must insert at least: "
+
(price - balance) +
" cents."
);
}
}
/**
* Return the money in the balance.
* The balance is cleared.
*/
Search WWH ::
Custom Search