Java Reference
In-Depth Information
The variable amount stores the amount entered from the console (line 11). This variable is
not changed, because the amount has to be used at the end of the program to display the
results. The program introduces the variable remainingAmount (line 13) to store the chang-
ing remaining amount.
The variable amount is a double decimal representing dollars and cents. It is converted to
an int variable remainingAmount , which represents all the cents. For instance, if amount
is 11.56 , then the initial remainingAmount is 1156 . The division operator yields the inte-
ger part of the division, so 1156 / 100 is 11 . The remainder operator obtains the remainder
of the division, so 1156 % 100 is 56 .
The program extracts the maximum number of singles from the remaining amount and
obtains a new remaining amount in the variable remainingAmount (lines 16-17). It then
extracts the maximum number of quarters from remainingAmount and obtains a new
remainingAmount (lines 20-21). Continuing the same process, the program finds the max-
imum number of dimes, nickels, and pennies in the remaining amount.
One serious problem with this example is the possible loss of precision when casting a
double amount to an int remainingAmount . This could lead to an inaccurate result. If you
try to enter the amount 10.03 , 10.03 * 100 becomes 1002.9999999999999 . You will
find that the program displays 10 dollars and 2 pennies. To fix the problem, enter the amount
as an integer value representing cents (see Exercise 2.24).
As shown in the sample run, 0 dimes, 1 nickels, and 1 pennies are displayed in the result.
It would be better not to display 0 dimes, and to display 1 nickel and 1 penny using the sin-
gular forms of the words. You will learn how to use selection statements to modify this pro-
gram in the next chapter (see Exercise 3.7).
loss of precision
2.26
Use print statements to find out the ASCII code for '1' , 'A' , 'B' , 'a' , and 'b' .
Use print statements to find out the character for the decimal codes 40 , 59 , 79 , 85 ,
and 90 . Use print statements to find out the character for the hexadecimal code 40 ,
5A , 71 , 72 , and 7A .
Check
Point
2.27
Which of the following are correct literals for characters?
'1' , '\u345dE' , '\u3fFa' , '\b' , '\t'
2.28
How do you display the characters \ and " ?
2.29
Evaluate the following:
int i = '1' ;
int j = '1' + '2' *( '4' - '3' )+ 'b' / 'a' ;
int k = 'a' ;
char c = 90 ;
2.30
Can the following conversions involving casting be allowed? If so, find the con-
verted result.
char c = 'A' ;
int i = ( int )c;
float f = 1000.34f ;
int i = ( int )f;
double d = 1000.34 ;
int i = ( int )d;
int i = 97 ;
char c = ( char )i;
 
Search WWH ::




Custom Search