Java Reference
In-Depth Information
/** Return the area of the triangle. */
public static double
area(
double
side1,
double
side2,
double
side3)
Write a test program that reads three sides for a triangle and computes the area if
the input is valid. Otherwise, it displays that the input is invalid. The formula for
computing the area of a triangle is given in Programming Exercise 2.19.
*6.20
(
Count the letters in a string
) Write a method that counts the number of letters in
a string using the following header:
public static int
countLetters(String s)
Write a test program that prompts the user to enter a string and displays the num-
ber of letters in the string.
*6.21
(
Phone keypads
) The international standard letter/number mapping for telephones
is shown in Programming Exercise 4.15. Write a method that returns a number,
given an uppercase letter, as follows:
int
getNumber(
char
uppercaseLetter)
Write a test program that prompts the user to enter a phone number as a string.
The input number may contain letters. The program translates a letter (uppercase
or lowercase) to a digit and leaves all other characters intact. Here is a sample run
of the program:
Enter a string: 1-800-Flowers
1-800-3569377
Enter a string: 1800flowers
18003569377
**6.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,
next-
Guess
becomes
lastGuess
and the approximation process continues. Imple-
ment the following method that returns the square root of
n
.
public static double
sqrt(
long
n)
*6.23
(
Occurrences of a specified character
) Write a method that finds the number of
occurrences of a specified character in a string using the following header:
public static int
count(String str,
char
a)
Search WWH ::
Custom Search