Java Reference
In-Depth Information
L
ISTING
4.4
HexDigit2Dec.java
1
import
java.util.Scanner;
2
3
public class
HexDigit2Dec {
4
public static void
main(String[] args) {
5 Scanner input =
new
Scanner(System.in);
6 System.out.print(
"Enter a hex digit: "
);
7 String hexString = input.nextLine();
8
9
// Check if the hex string has exactly one character
10
if
(hexString.length() !=
1
) {
11 System.out.println(
"You must enter exactly one character"
);
12 System.exit(
1
);
13 }
14
15
// Display decimal value for the hex digit
16
char
ch = hexString.charAt(
0
);
17
if
(ch <=
'F'
&& ch >=
'A'
) {
18
int
value = ch -
'A'
+
10
;
19 System.out.println(
"The decimal value for hex digit "
20 + ch +
" is "
+ value);
21 }
22
else if
(Character.isDigit(ch)) {
23 System.out.println(
"The decimal value for hex digit "
24 + ch +
" is "
+ ch);
25 }
26
else
{
27 System.out.println(ch +
" is an invalid input"
);
28 }
29 }
30 }
VideoNote
Convert hex to decimal
input string
check length
is A-F?
is 0-9?
Enter a hex digit: AB7C
You must enter exactly one character
Enter a hex digit: B
The decimal value for hex digit B is 11
Enter a hex digit: 8
The decimal value for hex digit 8 is 8
Enter a hex digit: T
T is an invalid input
The program reads a string from the console (line 7) and checks if the string contains a
single character (line 10). If not, report an error and exit the program (line 12).
The program invokes the
Character.toUpperCase
method to obtain the character
ch
as
an uppercase letter (line 16). If
ch
is between
'A'
and
'F'
(line 17), the corresponding deci-
mal value is
ch - 'A' + 10
(line 18). Note that
ch - 'A'
is
0
if
ch
is
'A'
,
ch - 'A'
isĀ
1
Search WWH ::
Custom Search