126 NumberFormatException Listing 68 implements the hex2DecS
*12.6 (NumberFormatException) Listing 6.8 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. *JAVA*
Solution
import java.util.Scanner;
public class HexToDecimal {
public static void main(String[] args) {
System.out.print(\"Enter Hexadecimal:\");
Scanner scan = new Scanner(System.in); // crating scan object
String input = scan.nextLine();// taking line of chars as input
try{ // try block
Integer Decimal = Integer.parseInt(input, 16);// converting input to decimal
System.out.println(\"Decimal Equivalent : \"+Decimal);// displying decimalnumber
}
catch(NumberFormatException exception){
System.out.println(\"Invalid Input\"+exception.getMessage()); // printing exception message
}
finally{ scan.close();// final block
}
}
}
