Java Reference
In-Depth Information
Code 2.8
continued
A more sophisticated
TicketMachine
public int refundBalance()
{
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
}}
}
2.13
Making choices: the conditional statement
Code 2.8 shows the internal details of the better ticket machine's class definition. Much of this defi-
nition will already be familiar to you from our discussion of the naïve ticket machine. For instance,
the outer wrapping that names the class is the same, because we have chosen to give this class the
same name. In addition, it contains the same three fields to maintain object state, and these have been
declared in the same way. The constructor and the two get methods are also the same as before.
The first significant change can be seen in the insertMoney method. We recognized that the
main problem with the naïve ticket machine was its failure to check certain conditions. One of
those missing checks was on the amount of money inserted by a customer, as it was possible for
a negative amount of money to be inserted. We have remedied that failing by making use of a
conditional statement to check that the amount inserted has a value greater than zero:
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println("Use a positive amount rather than: " +
amount);
}
Conditional statements are also known as if statements , from the keyword used in most pro-
gramming languages to introduce them. A conditional statement allows us to take one of two
possible actions based upon the result of a check or test. If the test is true, then we do one thing;
otherwise, we do something different. This kind of either/or decision should be familiar from
situations in everyday life: for instance, if I have enough money left, then I shall go out for a
meal; otherwise, I shall stay home and watch a movie. A conditional statement has the general
form described in the following pseudo-code :
Concept:
A conditional
statement takes
one of two possible
actions based upon
the result of a test.
if( perform some test that gives a true or false result ) {
Do the statements here if the test gave a true result
}
else {
Do the statements here if the test gave a false result
}
 
 
Search WWH ::




Custom Search