第二道自定义异常类~题~~amazing
~~
这次一个包全写在一起了,一个主函数 + 两个类
实现代码:
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");
}
}