Java Reference
In-Depth Information
Pay attention to the scope highlighting. You will quickly get used to the way well-
structured code looks. Try removing a curly bracket in the editor or adding one at an
arbitrary location, and observe how the coloring changes. Get used to recognizing when
scopes look wrong.
Exercise 2.52 After a ticket has been printed, could the value in the balance field ever be
set to a negative value by subtracting price from it? Justify your answer.
Exercise 2.53 So far, we have introduced you to two arithmetic operators, + and -, that can
be used in arithmetic expressions in Java. Take a look at Appendix C to find out what other
operators are available.
Exercise 2.54 Write an assignment statement that will store the result of multiplying two
variables, price and discount , into a third variable, saving .
Exercise 2.55 Write an assignment statement that will divide the value in total by the
value in count and store the result in mean .
Exercise 2.56 Write an if statement that will compare the value in price against the value
in budget . If price is greater than budget , then print the message “Too expensive”; other-
wise print the message “Just right”.
Exercise 2.57 Modify your answer to the previous exercise so that the message includes
the value of your budget if the price is too high.
Local variables
So far, we have met two different sorts of variables: fields (instance variables) and param-
eters. We are now going to introduce a third kind. All have in common that they store data,
but each sort of variable has a particular role to play.
Section 2.6 noted that a method body (or, in general, a block ) can contain both declarations and
statements. To this point, none of the methods we have looked at contain any declarations. The
refundBalance method contains three statements and a single declaration. The declaration
introduces a new kind of variable:
A local variable is
a variable declared
and used within a
single method. Its
scope and lifetime
are limited to that
of the method.
public int refundBalance()
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
Search WWH ::

Custom Search