[英]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)
使用一個簡單的方法,如果發生NumberFormatException
則return 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.