十六進位制數轉換為十進位制,用java實現
阿新 • • 發佈:2021-02-03
十六進位制記數系統有16個數字:09,AF。字母A、B、C、D、E和F對應於十進位制數字10、11、12、13、14和15。
程式碼:
package com.zhuo.base.com.zhuo.base;
import java.util.Scanner;
public class HexDigit {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex digit: " );
String hexString = input.nextLine();
//檢查十六進位制字串是否只有一個字元
if (hexString.length() != 1) {
System.out.println("You must enter exactly one character");
System.exit(1);
}
//顯示十六進位制數字的十進位制值
char ch = Character.toUpperCase(hexString. charAt(0));
if (ch <= 'F' && ch >= 'A') {
int value = ch - 'A' + 10;
System.out.println("The decimal value for hex digit " + ch + " is " + value);
}
else if (Character.isDigit(ch)) {
System.out.println("The decimal value for hex digit " + ch +" is " + ch);
}
else {
System.out.println(ch + " is an invalid input");
}
}
}
結果顯示