Java Reference
In-Depth Information
P
ROGRAMMING
E
XERCISES
Pedagogical Note
The exercises in Chapters 9-13 help you achieve three objectives:
■
Design classes and draw UML class diagrams.
■
Implement classes from the UML.
■
Use classes to develop applications.
Students can download solutions for the UML diagrams for the even-numbered exer-
cises from the Companion Website, and instructors can download all solutions from
the same site.
Sections 9.2-9.5
9.1
three objectives
(
The
Rectangle
class
) Following the example of the
Circle
class in Section 9.2,
design a class named
Rectangle
to represent a rectangle. The class contains:
Two
double
data fields named
width
and
height
that specify the width and
height of the rectangle. The default values are
1
for both
width
and
height
.
■
A no-arg constructor that creates a default rectangle.
■
A constructor that creates a rectangle with the specified
width
and
height
.
■
A method named
getArea()
that returns the area of this rectangle.
■
A method named
getPerimeter()
that returns the perimeter.
Draw the UML diagram for the class and then implement the class. Write a test
program that creates two
Rectangle
objects—one with width
4
and height
40
and the other with width
3.5
and height
35.9
. Display the width, height, area,
and perimeter of each rectangle in this order.
■
9.2
(
The
Stock
class
) Following the example of the
Circle
class in Section 9.2,
design a class named
Stock
that contains:
■
A string data field named
symbol
for the stock's symbol.
■
A string data field named
name
for the stock's name.
■
A
double
data field named
previousClosingPrice
that stores the stock
price for the previous day.
■
A
double
data field named
currentPrice
that stores the stock price for the
current time.
■
A constructor that creates a stock with the specified symbol and name.
■
A method named
getChangePercent()
that returns the percentage changed
from
previousClosingPrice
to
currentPrice
.
Draw the UML diagram for the class and then implement the class. Write a test
program that creates a
Stock
object with the stock symbol
ORCL
, the name
Oracle Corporation
, and the previous closing price of
34.5
. Set a new current
price to
34.35
and display the price-change percentage.
Section 9.6
*9.3
(
Use the
Date
class
) Write a program that creates a
Date
object, sets its elapsed
time to
10000
,
100000
,
1000000
,
10000000
,
100000000
,
1000000000
,
10000000000
, and
100000000000
, and displays the date and time using the
toString()
method, respectively.
*9.4
(
Use the
Random
class
) Write a program that creates a
Random
object with seed
1000
and displays the first 50 random integers between
0
and
100
using the
nextInt(100)
method.
Search WWH ::
Custom Search