Java Reference
In-Depth Information
2.14
A further conditional-statement example
The printTicket method contains a further example of a conditional statement. Here it is
in outline:
if(balance >= price) {
Printing details omitted.
// 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) + " more cents.");
}
We wish to remedy the fact that the naïve version makes no check that a customer has inserted
enough money to be issued a ticket. This version checks that the value in the balance field is
at least as large as the value in the price field. If it is, then it is okay to print a ticket. If it is not,
then we print an error message instead.
The printing of the error message follows exactly the same pattern as we saw for printing the
price of tickets in the printTicket method; it is just a little more verbose.
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");
The single actual parameter to the println method consists of a concatenation of three ele-
ments: two string literals on either side of a numeric value. In this case, the numeric value is a
subtraction that has been placed in parentheses to indicate that it is the resulting value we wish
to concatenate with the two strings.
Exercise 2.50 In this version of printTicket , we also do something slightly different with
the total and balance fields. Compare the implementation of the method in Code 2.1 with
that in Code 2.8 to see whether you can tell what those differences are. Then check your un-
derstanding by experimenting within BlueJ.
Exercise 2.51 Is it possible to remove the else part of the if statement in the printTicket
method (i.e., remove the word else and the block attached to it)? Try doing this and seeing
if the code still compiles. What happens now if you try to print a ticket without inserting any
money?
 
 
Search WWH ::




Custom Search