【JAVA 课后习题 12.5】+ 自定义异常类

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练习,JAVA,课后习题及知识点总结)