Java Reference
In-Depth Information
24 decimal = decimal /
16
;
25 }
26
27 System.out.println(
"The hex number is "
+ hex);
28 }
29 }
get a hex char
get a letter
Enter a decimal number: 1234
The hex number is 4D2
line#
decimal
hex
hexValue
hexDigit
14
1234
""
17
2
iteration 1
23
"2"
2
24
77
17
13
iteration 2
23
"D2"
D
24
4
17
4
iteration 3
23
"4D2"
4
24
0
The program prompts the user to enter a decimal integer (line 11), converts it to a hex num-
ber as a string (lines 14-25), and displays the result (line 27). To convert a decimal to a hex
number, the program uses a loop to successively divide the decimal number by
16
and obtain
its remainder (line 17). The remainder is converted into a hex character (lines 20-21). The
character is then appended to the hex string (line 23). The hex string is initially empty (line
14). Divide the decimal number by
16
to remove a hex digit from the number (line 24). The
loop ends when the remaining decimal number becomes
0
.
The program converts a
hexValue
between
0
and
15
into a hex character. If
hexValue
is
between
0
and
9
, it is converted to
(char)(hexValue + '0')
(line 21). Recall that when
adding a character with an integer, the character's Unicode is used in the evaluation. For
example, if
hexValue
is
5
,
(char)(hexValue + '0')
returns
5
. Similarly, if
hexValue
is between
10
and
15
, it is converted to
(char)(hexValue - 10 + 'A')
(line 21). For
instance, if
hexValue
is
11
,
(char)(hexValue - 10 + 'A')
returns
B
.
5.21
✓
✓
Will the program work if
n1
and
n2
are replaced by
n1 / 2
and
n2 / 2
in line 17
in Listing 5.9?
Check
Point
5.22
In Listing 5.11, why is it wrong if you change the code
(char)(hexValue + '0')
to
hexValue + '0'
in line 21?
5.23
In Listing 5.11, how many times the loop body is executed for a decimal number
245
and how many times the loop body is executed for a decimal number
3245
?
Search WWH ::
Custom Search