Java Reference
In-Depth Information
2.9
Printing from methods
Code 2.7 shows the most complex method of the class:
printTicket
. To help your understand-
ing of the following discussion, make sure that you have called this method on a ticket machine.
You should have seen something like the following printed in the BlueJ terminal window:
##################
# The BlueJ Line
# Ticket
# 500 cents.
##################
This is the longest method we have seen so far, so we shall break it down into more manageable
pieces:
■
The header indicates that the method has a
void
return type and that it takes no parameters.
■
The body comprises eight statements plus associated comments.
■
The first six statements are responsible for printing what you see in the BlueJ terminal win-
dow: five lines of text and a sixth, blank line.
■
The seventh statement adds the balance inserted by the customer (through previous calls to
insertMoney
) to the running total of all money collected so far by the machine.
■
The eighth statement resets the balance to zero with a basic assignment statement, ready for
the next customer.
Code 2.7
The
printTicket
method
/**
* Print a ticket and reduce the
* current balance to zero.
*/
public
void
printTicket()
{
// 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 balance.
total = total + balance;
// Clear the balance.
balance = 0;
}
Search WWH ::
Custom Search