繁体   English   中英

十六进制字符串到Java中的整数解析异常处理

[英]hex string to Integer parsing exception handling in java

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

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

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

将其放在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.
}

对于输入字符串:“ 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;
}

可以捕获异常并返回零。

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

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

我如何避免它(例如返回0)

使用一个简单的方法,如果发生NumberFormatExceptionreturn 0

public int getHexValue(String hex){

    int result = 0;

    try {
        result = Integer.parseInt(hex, 16);
     } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return result;
}

只需捕获异常并设置默认值即可。 但是,您需要在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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM