(NumberFormatException) Listing 1 implements the hex2Dec(String hexString) method, which converts a hex string into a decimal number. Implement the hex2Dec method to throw a NumberFormatException if the string is not a hex string.
LISTING 1 Hex2Dec.java
1 import java.util.Scanner;
2
3 public class Hex2Dec {
4 /** Main method */
5 public static void main(String[] args) {
6 // Create a Scanner
7 Scanner input = new Scanner(System.in);
8
9 // Prompt the user to enter a string
10 System.out.print("Enter a hex number: ");
11 String hex = input.nextLine();
12
13 System.out.println("The decimal value for hex number "
14 + hex + " is " + hexToDecimal(hex.toUpperCase()));
15 }
16
17 public static int hexToDecimal(String hex) {
18 int decimalValue = 0;
19 for (int i = 0; i
20 char hexChar = hex.charAt(i);
21 decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
22 }
23
24 return decimalValue;
25 }
26
27 public static int hexCharToDecimal(char ch) {
28 if (ch >= 'A' && ch <= 'F')
29 return 10 + ch - 'A';
30 else // ch is '0', '1', ..., or '9'
31 return ch - '0';
32 }
33 }
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.