Java Reference
In-Depth Information
6.9
(Rounding Numbers)
Math.floor
can be used to round values to the nearest integer—e.g.,
y = Math.floor(x +
0.5
);
will round the number
x
to the nearest integer and assign the result to
y
. Write an application that
reads
double
values and uses the preceding statement to round each of the numbers to the nearest
integer. For each number processed, display both the original number and the rounded number.
6.10
(Rounding Numbers)
T
o round numbers to specific decimal places, use a statement like
y = Math.floor(x *
10
+
0.5
) /
10
;
which rounds
x
to the tenths position (i.e., the first position to the right of the decimal point), or
y = Math.floor(x *
100
+
0.5
) /
100
;
which rounds
x
to the hundredths position (i.e., the second position to the right of the decimal
point). Write an application that defines four methods for rounding a number
x
in various ways:
a)
roundToInteger(number)
b)
roundToTenths(number)
c)
roundToHundredths(number)
d)
roundToThousandths(number)
For each value read, your program should display the original value, the number rounded to the
nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hun-
dredth and the number rounded to the nearest thousandth.
6.11
Answer each of the following questions:
a)
What does it mean to choose numbers “at random”?
b)
Why is the
nextInt
method of class
SecureRandom
useful for simulating games of
chance?
c)
Why is it often necessary to scale or shift the values produced by a
SecureRandom
object?
d)
Why is computerized simulation of real-world situations a useful technique?
6.12
Write statements that assign random integers to the variable
n
in the following ranges:
a)
≤
≤
1
n
2.
≤
≤
b)
1
n
100.
≤
≤
c)
0
n
9.
≤
≤
d)
1000
n
1112.
e)
-1
≤
n
≤
1.
11.
6.13
Write statements that will display a random number from each of the following sets:
a) 2, 4, 6, 8, 10.
b) 3, 5, 7, 9, 11.
c) 6, 10, 14, 18, 22.
6.14
(Exponentiation)
Write a method
integerPower(base,
exponent)
that returns the value of
base
exponent
For example,
integerPower(3,
4)
calculates
3
4
(or
3
*
3
*
3
*
3
). Assume that
exponent
is a posi-
tive, nonzero integer and that
base
is an integer. Use a
for
or
while
statement to control the calcu-
lation. Do not use any
Math
class methods. Incorporate this method into an application that reads
integer values for
base
and
exponent
and performs the calculation with the
integerPower
method.
6.15
(Hypotenuse Calculations)
Define a method
hypotenuse
that calculates the hypotenuse of
a right triangle when the lengths of the other two sides are given. The method should take two ar-
guments of type
double
and return the hypotenuse as a
double
. Incorporate this method into an
f)
-3
≤
n
≤