题目:18.24 (将十六进制数转换为十进制数)
编写一个递归方法,将一个字符串形式的十六进制数转换为一个十进制数。方法头如下:
java
public static int hex2Dec(String hexString)
编写一个测试程序,提示用户输入一个十六进制字符串,然后显示等价的十进制数。
代码示例
编程练习题18_24ConvertHexadecimalToDecimal.java
java
package chapter_18;
import java.util.Scanner;
public class 编程练习题18_24ConvertHexadecimalToDecimal {
private static int pow = 0;
private static int decimal = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hexadecimal number: ");
String hex = input.next();
System.out.println(hex2Dec(hex));
input.close();
}
public static int hex2Dec(String hexString){
if(hexString.length()==0)
return decimal;
char ch = hexString.charAt(hexString.length()-1);
int value = 0;
if(ch>='A'&&ch<='F') {
value = (int)ch-55;
}else
value = Integer.valueOf(ch+"");
decimal += value * (int)Math.pow(16, pow);
pow++;
return hex2Dec(hexString.substring(0,hexString.length()-1));
}
}
输出结果
java
Enter a hexadecimal number: 1A3F
6719