16進数を10進数に変換

4745 ワード

朝早くにJAVAの基本コードを叩きに来て、脳を補います。土曜日も出勤します。
需要:コンソールから16進数文字列を入力し、10進数を出力します。
コードはjavaプログラム設計の基礎部分を参考にしています。
直接コード:
public class Hex2Decimal {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        while (true) {
            System.out.print("          : ");
            String hexStr = input.nextLine();

            //       
            int decimalValue = hexToDecimal(hexStr.toUpperCase());

            //     
            System.out.println("         : " + decimalValue);
            System.out.println();
        }

    }

    //                   
    private static int hexToDecimal(String hexStr) {
        int decimalValue = 0;
        for (int i = 0; i < hexStr.length(); i++) {
            //            
            char hexChar = hexStr.charAt(i);
            //   
            decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
        }
        return decimalValue;
    }

    //               
    private static int hexCharToDecimal(char ch) {
        if (ch >= 'A' && ch <= 'F') {
            return 10 + ch - 'A';
        } else {
            return ch - '0';
        }

    }

}