The hexadecimal number is converted to decimal, which is realized by java

1. Introduction

The hexadecimal numbering system has 16 numbers: 0-9, AF. The letters A, B, C, D, E, and F correspond to the decimal numbers 10, 11, 12, 13, 14, and 15.

2. Code

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");
        }
    }
}

Three. Results display

Insert picture description here
Insert picture description hereInsert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113563694