十六进制转十进制

十六进制数转换成十进制数

package com.studyJava.stringStudy;

import java.util.Scanner;

public class hexToDecimal {

    public static void main(String[] args){
        Scanner input =new Scanner(System.in);
        String str =input.nextLine();
        int result = hexToDecimal(str.toUpperCase());
        System.out.println(str+"对应的十进制数是:" + result);
    }

    private static int hexToDecimal(String str) {
        int sum =0;
        for(int i =0 ;i<str.length();i++){
            char ch = str.charAt(i);
            try {
                sum = sum * 16 + decimal(ch);
            } catch (Exception e) {                
                e.printStackTrace();
            }
        }
        return sum;
    }

    private static int decimal(char ch) throws Exception {
        if(ch>='A'&&ch<='F'){
            return 10 +ch -'A';
        }else if(ch>='0'&&ch<='9'){
            return ch -'0';
        }else{
        throw new Exception("十六进制数不合理,请重新输入");
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/yuwenfeng/p/3094764.html