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
相关推荐
Book_熬夜!几秒前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
无问81710 分钟前
数据结构-排序(冒泡,选择,插入,希尔,快排,归并,堆排)
java·数据结构·排序算法
m0_6312704027 分钟前
高级c语言(五)
c语言·开发语言
customer0830 分钟前
【开源免费】基于SpringBoot+Vue.JS在线文档管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
2401_8582861133 分钟前
53.【C语言】 字符函数和字符串函数(strcmp函数)
c语言·开发语言
Flying_Fish_roe1 小时前
Spring Boot-版本兼容性问题
java·spring boot·后端
程序猿进阶1 小时前
如何在 Visual Studio Code 中反编译具有正确行号的 Java 类?
java·ide·vscode·算法·面试·职场和发展·架构
程序猿练习生1 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
slandarer1 小时前
MATLAB | R2024b更新了哪些好玩的东西?
java·数据结构·matlab
2401_858120261 小时前
MATLAB中的无线通信系统部署和优化工具有哪些
开发语言·matlab