1 public class Test02{
2
3 public static void main(String[] args){
4 while(true)
5 {
6 System.out.print("Please input an Hexadecimal(input "exit" or "bye" quit):");
7
8 Scanner s = new Scanner(System.in);
9
10 //输入字符串直接都转换成小写
11 String str = s.next().toLowerCase();
12
13
14 //退出函数
15 method m = new method();
16 if(m.Data_Judegment(str))
17 break;
18
19
20 //判断输入的字符串是否满足要求
21 Data_Judgement DJ = new Data_Judgement();
22 boolean b1 = DJ.Judgement_Int(str);
23 if(b1 == false)
24 {
25 continue;
26 }
27
28 //十六进制转换成十进制
29 DataConvert DC = new DataConvert();
30 DC.Decimal_To_Hexadecimal(str);
31 }
32
33 }
34 }
35
36
37 //十六进制转换成十进制
38
39
40 class DataConvert{
41 public void Decimal_To_Hexadecimal(String n){
42 long L_sum = 0;
43 int x = 0;
44
45 int j = 0;
46 for(int i=n.length();i>0;i--){
47 //System.out.println(n.charAt(i-1));
48 switch(n.charAt(i-1)){
49
50 //因为上面已经对输入字符串转换,可以注释掉大写字母的case语句
51 case 'a':
52 case 'A':
53 x = 10;
54 break;
55 case 'b':
56 case 'B':
57 x = 11;
58 break;
59 case 'c':
60 case 'C':
61 x = 12;
62 break;
63 case 'd':
64 case 'D':
65 x = 13;
66 break;
67 case 'e':
68 case 'E':
69 x = 14;
70 break;
71 case 'f':
72 case 'F':
73 x = 15;
74 break;
75 default :
76 //‘0-9’ 将单个字符转换成整型,直接用(int)强制转换会转成ASCII值
77 x = n.charAt(i-1) - '0';
78 //System.out.println(x);
79 break;
80 }
81 L_sum += x*Math.pow(16,j++);
82 }
83
84 System.out.println(L_sum);
85 }
86 };
87
88
89 //判断输入字符串是否满足0-9、a-f、A-F
90
91
92 class Data_Judgement{
93 public boolean Judgement_Int(String n){
94
95 for(int i=0;i<n.length();i++){
96 if(!n.matches("[a-fA-F0-9_u4e00-u9fa5]*")){
97 System.out.println("输入字符串不正确!");
98 return false;
99 }
100 }
101 return true;
102
103 }
104 };
105
106 // 退出函数
107
108
109 class method{
110 boolean Data_Judegment(String str)
111 {
112 //trim() 去除字符串两边的不可见字符,包括 空格、回车符、制表符等
113 if("exit".equals(str.trim()) || "bye".equals(str.trim()))
114 return true;
115 else
116 return false;
117 }
118 };