DecimalFormat class in lecture, you
might have gotten the impression that you have to know at the time you
write the code how many decimal places (i.e., digits to the right of
the decimal point) you want to print. The example we saw, in CircleStats.java, uses
a format string of "0.######" to indicate 6 decimal
places.
If you're a little clever, however, you can determine the number of
decimal places at run time (i.e., when your program is
running, rather than when you write and compile it). The trick is to
form a format string that you give to the DecimalFormat
constructor at run time by concatenating one # at a time.
How do you concatenate a character onto a String object?
Pretty much like you've been doing all along: with the +
operator, applied to String objects.
Consider the following code fragment:
pattern is the concatenation
of the two-character string "0." with the one-character
string "#", so that pattern is
"0.#". In other words, it's the same as having written
Could we then concatenate on another one-character "#"
string, giving us a pattern string of
"0.##"? As a certain former governor and
vice-presidential candidate would say, you betcha! We can concatenate
as many one-character "#" strings as we like.
Now consider some integer j. How could we form a
pattern string that is "0." followed by
j # characters? Simple: start with
pattern being "0." and then concatenate
"#" onto pattern j times. How do we
perform an action some variable number of times? Can you say
"for-loop"? I knew you could!
Your mission is to write a program that does the following:
double, say x,
and reads it in.
places, and reads it in.
pattern, consisting
of "0." followed by # repeated
places times.
DecimalFormat object, say
fmt, from pattern.
x, the number of decimal places asked for, and
the square of x. When printing the value of
x, use the default number of decimal places, but
when printing the value of x squared, use the
number of places requested by means of a judicious use of
fmt.
Use the CircleStats.java program as a guide. Don't forget that you'll
need to import both java.util.Scanner and
java.text.DecimalFormat.
Remember that the easy way to square a number is to simply multiply
it by itself: x * x.
You will find that if you ask for more than 16 decimal places, you get
only 16. Don't worry about that; it's OK. You will also find that if
fewer than the number asked for are needed, then fewer are used; for
example, the square of 4 will print as 16 no matter what.
Furthermore, any trailing 0s will be trimmed off, so that if you're
formatting 1.005 to two decimal places, you get 1. rather
than 1.00. Also, it's OK if you give 0 decimal places in
the event that the user asks for a negative number of them, since
that's how DecimalFormat objects work.
Turn in a listing of your program and the result of three runs. One of the runs should ask for 0 decimal places.