用java写一个程序“写一个程序,实现十六进制与十进制之间的相互转换,要求自定义方法实现,不得调用Interger.parseInt或者Integer.toHexstring,方法头分别定义为public static String intToHex(int num)和public static int hexToInt(String hstr)。 程序运行时,提供两个选项,分别表示不同的转换,”
时间: 2023-05-18 19:04:32 浏览: 210
好的,我可以回答这个问题。以下是代码示例:
public class HexConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请选择转换类型:");
System.out.println("1. 十进制转十六进制");
System.out.println("2. 十六进制转十进制");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入一个十进制数:");
int num = scanner.nextInt();
String hex = intToHex(num);
System.out.println("转换结果为:" + hex);
break;
case 2:
System.out.println("请输入一个十六进制数:");
String hstr = scanner.next();
int dec = hexToInt(hstr);
System.out.println("转换结果为:" + dec);
break;
default:
System.out.println("无效的选项!");
break;
}
}
public static String intToHex(int num) {
StringBuilder sb = new StringBuilder();
while (num > 0) {
int remainder = num % 16;
if (remainder < 10) {
sb.append((char) ('0' + remainder));
} else {
sb.append((char) ('A' + remainder - 10));
}
num /= 16;
}
return sb.reverse().toString();
}
public static int hexToInt(String hstr) {
int num = 0;
for (int i = 0; i < hstr.length(); i++) {
char c = hstr.charAt(i);
int digit = 0;
if (c >= '0' && c <= '9') {
digit = c - '0';
} else if (c >= 'A' && c <= 'F') {
digit = c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
digit = c - 'a' + 10;
} else {
throw new IllegalArgumentException("无效的十六进制数:" + hstr);
}
num = num * 16 + digit;
}
return num;
}
}
希望这个程序能够满足您的需求。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)