gpt4 book ai didi

Java:格式化数字错误?

转载 作者:行者123 更新时间:2023-12-03 23:19:56 28 4
gpt4 key购买 nike

我遇到了一个关于使用字符串输入和输出转换数字格式的类的问题:

public class Conversion{

static int result;

public static String fromHexToDec (String clientInput) {
result= Integer.parseInt(clientInput, 10);
return Integer.toString(result);
}

public static String fromDecToHex (String clientInput) {
result= Integer.parseInt(clientInput, 16);
return Integer.toString(result);
}

public static String fromOctTo4 (String clientInput) {
result= Integer.parseInt(clientInput, 4);
return Integer.toString(result);
}

public static String from4ToOct(String clientInput) {
result= Integer.parseInt(clientInput, 8);
return Integer.toString(result);
}

public static String formBinToDec(String clientInput) {
result= Integer.parseInt(clientInput, 10);
return Integer.toString(result);
}

public static String fromDecToBin(String clientInput) {
result= Integer.parseInt(clientInput, 2);
return Integer.toString(result);
}

public static String from5To7(String clientInput) {
result= Integer.parseInt(clientInput, 7);
return Integer.toString(result);
}

public static String from7To5(String clientInput) {
result= Integer.parseInt(clientInput, 5);
return Integer.toString(result);
}

我在尝试在 main 方法中运行 fromHexToDec 时收到此错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "C"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Konverzija.fromHexToDec(Conversion.java:9)
at Test.main(Test.java:5)

有人可以帮忙吗?

最佳答案

因为

public static String fromHexToDec (String clientInput) {
result= Integer.parseInt(clientInput, 10);
return Integer.toString(result);
}

将基数 10 传递给 parseInt()(这在十进制中无效)。用16个赞

public static String fromHexToDec (String clientInput) {
result= Integer.parseInt(clientInput, 16);
return Integer.toString(result);
}

fromDecToHex 应该是

public static String fromDecToHex(String clientInput) {
int result = Integer.parseInt(clientInput, 10);
return Integer.toString(result, 16);
}

public static String fromDecToHex(String clientInput) {
int result = Integer.parseInt(clientInput);
return String.format("%02X", result);
}

第二个具有零填充的潜在优势。

关于Java:格式化数字错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626864/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com