[英]hex string to Integer parsing exception handling in java
I need to parse string hex value to the Integer value. 我需要将字符串十六进制值解析为Integer值。 Like this:
像这样:
String hex = "2A"; //The answer is 42
int intValue = Integer.parseInt(hex, 16);
But when I insert an incorrect hex value (for example "LL") then I get java.lang.NumberFormatException: For input string: "LL"
How I can avoid it (for example return 0)? 但是,当我插入错误的十六进制值(例如“ LL”)时,我得到
java.lang.NumberFormatException: For input string: "LL"
我如何避免它(例如返回0)?
Enclose it in a try catch block. 将其放在try catch块中。 That is how Exception Handling works: -
这就是异常处理的工作方式:-
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.
}
For input string: "LL" How I can avoid it (for example return 0)?
对于输入字符串:“ LL”我如何避免使用它(例如返回0)?
Just catch the exception and assign zero to intvalue 只需捕获异常并将零分配给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;
}
You can catch the exception and return zero instead. 您可以捕获异常并返回零。
public static int parseHexInt(String hex) {
try {
return Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
return 0;
}
}
However, I recommend re-evaluating your approach, as 0 is a valid hex number as well, and doesn't signify invalid input such as "LL"
. 但是,我建议您重新评估您的方法,因为0也是一个有效的十六进制数,并且不表示无效的输入,例如
"LL"
。
How I can avoid it (for example return 0)
我如何避免它(例如返回0)
Using a simple method which will return 0
in case a NumberFormatException
occurrs 使用一个简单的方法,如果发生
NumberFormatException
则return 0
public int getHexValue(String hex){
int result = 0;
try {
result = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
Just catch the exception and set the default value. 只需捕获异常并设置默认值即可。 However, you need to declare the variable outside the
try
block. 但是,您需要在
try
块之外声明变量。
int intValue;
try {
intValue = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
intValue = 0;
}
If you need to set the value using an initializer expression (say, for a final
variable), you'll have to package up the logic in a method: 如果需要使用初始值设定项表达式(例如,
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.