Java语言程序设计基础篇_编程练习题18.24 (将十六进制数转换为十进制数)

题目:18.24 (将十六进制数转换为十进制数)

编写一个递归方法,将一个字符串形式的十六进制数转换为一个十进制数。方法头如下:

java 复制代码
public static int hex2Dec(String hexString)

编写一个测试程序,提示用户输入一个十六进制字符串,然后显示等价的十进制数。

代码示例

编程练习题18_24ConvertHexadecimalToDecimal.java

java 复制代码
package chapter_18;

import java.util.Scanner;

public class 编程练习题18_24ConvertHexadecimalToDecimal {
	private static int pow = 0;
	private static int decimal = 0;
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter a hexadecimal number: ");
		String hex = input.next();
		System.out.println(hex2Dec(hex));
		input.close();
	}
	public static int hex2Dec(String hexString){
		if(hexString.length()==0)
			return decimal;
		char ch = hexString.charAt(hexString.length()-1);
		int value = 0;
		if(ch>='A'&&ch<='F') {
			value = (int)ch-55;
		}else
			value = Integer.valueOf(ch+"");
		decimal += value * (int)Math.pow(16, pow);
		pow++;
		return hex2Dec(hexString.substring(0,hexString.length()-1));
	}

}
输出结果
java 复制代码
Enter a hexadecimal number: 1A3F
6719
相关推荐
小马爱打代码3 小时前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
岁忧3 小时前
GoLang五种字符串拼接方式详解
开发语言·爬虫·golang
tyatyatya3 小时前
MATLAB基础数据类型教程:数值型/字符型/逻辑型/结构体/元胞数组全解析
开发语言·matlab
小坏讲微服务3 小时前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z893 小时前
springboot 异步操作
java·spring boot·mybatis
i***13243 小时前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白3 小时前
后端:SpringMVC
java
IT_Octopus3 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88993 小时前
Spring详解
java·后端·spring
S***26753 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring