Java Reference
In-Depth Information
**5.22
(
Math: approximate the square root
) There are several techniques for implement-
ing the
sqrt
method in the
Math
class. One such technique is known as the
Babylonian method.
It approximates the square root of a number,
n
, by repeatedly
performing a calculation using the following formula:
nextGuess = (lastGuess + n / lastGuess) /
2
When
nextGuess
and
lastGuess
are almost identical,
nextGuess
is the
approximated square root. The initial guess can be any positive value (e.g.,
1
).
This value will be the starting value for
lastGuess
. If the difference between
nextGuess
and
lastGuess
is less than a very small number, such as
0.0001
,
you can claim that
nextGuess
is the approximated square root of
n
. If not,
nextGuess
becomes
lastGuess
and the approximation process continues.
Implement the following method that returns the square root of
n
.
public static double
sqrt(
long
n)
*5.23
(
Geometry: display angles
) Write a program that prompts the user to enter three
points of a triangle and displays the angles in degrees. Round the value to keep
two digits after the decimal point. The formula to compute angles A, B, and C are
as follows:
A = arccos((a * a - b * b - c * c) / (-2 * b * c))
B = arccos((b * b - a * a - c * c) / (-2 * a * c))
C = arccos((c * c - b * b - a * a) / (-2 * a * b))
x2, y2
a
B
c
C
x3, y3
A
b
x1, y1
Here is a sample run of the program:
Enter three points:
The three angles are 15.26 90.0 74.74
1 1 6.5 1 6.5 2.5
Sections 5.10-5.12
**5.24
(
Display current date and time
) Listing 2.6, ShowCurrentTime.java, displays the
current time. Improve this example to display the current date and time. The cal-
endar example in Listing 5.12, PrintCalendar.java, should give you some ideas on
how to find the year, month, and day.
**5.25
(
Convert milliseconds to hours, minutes, and seconds
) Write a method that
converts milliseconds to hours, minutes, and seconds using the following
header:
public static
String convertMillis(
long
millis)
The method returns a string as
hours:minutes:seconds
. For example,
convertMillis(5500)
returns a string 0:0:5,
convertMillis(100000)
returns a string
0:1:40
, and
convertMillis(555550000)
returns a string
154:19:10
.