Java Reference

In-Depth Information

3.8.3

The modulo operator

The last method in the
NumberDisplay
class increments the display value by 1. It takes

care that the value resets to 0 when the limit is reached:

public void increment()

{

value = (value + 1) % limit;

}

This method uses the
modulo
operator (
%
). The modulo operator calculates the remainder of an

integer division. For example, the result of the division

27 / 4

can be expressed in integer numbers as

result = 6, remainder = 3

The modulo operator returns just the remainder of such a division. Thus, the result of the ex-

pression
(27 % 4)
would be
3
.

Exercise 3.15
Explain the modulo operator. You may need to consult more resources (on-

line Java language resources, other Java books, etc.) to find out the details.

Exercise 3.16
What is the result of the expression
(8 % 3)
?

Exercise 3.17
Try out the expression
(8 % 3)
in the Code Pad. Try other numbers. What

happens when you use the modulo operator with negative numbers?

Exercise 3.18
What are all possible results of the expression
(n % 5)
, where
n
is an

integer variable?

Exercise 3.19
What are all possible results of the expression
(n % m)
, where
n
and
m
are

integer variables?

Exercise 3.20
Explain in detail how the increment method works.

Exercise 3.21
Rewrite the increment method without the modulo operator, using an if

statement. Which solution is better?

Exercise 3.22
Using the
clock-display
project in BlueJ, test the
NumberDisplay
class by

creating a few
NumberDisplay
objects and calling their methods.

3.8.4

Class
ClockDisplay

Now that we have seen how we can build a class that defines a two-digit number display, we shall

look in more detail at the
ClockDisplay
classâ€”the class that will create two number displays to

create a full time display. Code 3.4 shows the complete source code of the
ClockDisplay
class.

As with the
NumberDisplay
class, we shall briefly discuss all fields, constructors, and methods.

Search WWH ::

Custom Search