0

我需要将字符串十六进制值解析为整数值。像这样:

String hex = "2A"; //The answer is 42  
int intValue = Integer.parseInt(hex, 16);

但是当我插入不正确的十六进制值(例如“LL”)时,我会得到java.lang.NumberFormatException: For input string: "LL"如何避免它(例如返回 0)?

4

5 回答 5

1

将其包含在 try catch 块中。这就是异常处理的工作原理: -

int intValue = 0;
try {
    intValue = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
    System.out.println("Invalid Hex Value");
    // intValue will contain 0 only from the default value assignment.
}
于 2012-11-20T21:53:18.677 回答
1

对于输入字符串:“LL”我怎样才能避免它(例如返回 0)?

只需捕获异常并将分配给intvalue

int intValue;
try {
String hex = "2A"; //The answer is 42  
intValue = Integer.parseInt(hex, 16);
}
catch(NumberFormatException ex){
  System.out.println("Wrong Input"); // just to be more expressive
 invalue=0;
}
于 2012-11-20T21:53:19.373 回答
1

可以捕获异常并返回零。

public static int parseHexInt(String hex) {
    try {
        return Integer.parseInt(hex, 16);
    } catch (NumberFormatException e) {
        return 0;
    }
}

但是,我建议重新评估您的方法,因为 0 也是有效的十六进制数,并不表示无效输入,例如"LL".

于 2012-11-20T21:54:39.990 回答
0

我怎样才能避免它(例如返回 0)

使用一种简单的方法,return 0以防NumberFormatException万一

public int getHexValue(String hex){

    int result = 0;

    try {
        result = Integer.parseInt(hex, 16);
     } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return result;
}
于 2012-11-20T21:54:55.070 回答
0

只需捕获异常并设置默认值即可。但是,您需要在try块外声明变量。

int intValue;
try {
    intValue = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
    intValue = 0;
}

如果您需要使用初始化表达式(例如,对于final变量)设置值,则必须将逻辑打包在一个方法中:

public int parseHex(String hex) {
    try {
        return Integer.parseInt(hex, 16);
    } catch (NumberFormatException e) {
        return 0;
    }
}

// elsewhere...
final int intValue = parseHex(hex);
于 2012-11-20T21:55:04.097 回答