package He;
import java.util.Scanner;
public class He {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex number : ");
String st = input.nextLine();
System.out.println("The decimal value for hex number " + st + " is " + hT(st));
}
public static int hT(String st){
int a = 0;
for(int i = 0 ; i < st.length(); i++){
char s = st.charAt(i);
try{
CH(s);
}
catch (Exception ex){ // 捕获异常
System.out.println("Error");
}
a = a * 16 + ZH(s);
}
return a;
}
public static int ZH(char s){
if(s >= 'A' && s <= 'F')
return 10 + s - 'A';
else
return s - '0';
}
public static void CH(char s)
throws Exception{ // 申明抛出异常
if(! ((s >= 'A' && s <= 'F') || (s >= '0' && s <= '9' )))
throw new Exception("Error");
}
}
【JAVA 课后习题 12.5】+ 自定义异常类
最新推荐文章于 2023-10-10 22:40:36 发布