我正在使用第三方java jar文件将字符串转换为整数.
当字符串包含百分号"%"时,jar文件将抛出NumberFormatException.
下面是Jar文件的代码.
String str = "com%paq"; // this is the input string
//the jar file code starts here
byte[] b = new byte[1];
b[0] = (byte)(Integer.parseInt( str.substring( 2, 2 + 2 ), 16 ) & 0xFF);
s[j++] = (new String( b, 0, 1, "ASCII" )).charAt( 0 );
Run Code Online (Sandbox Code Playgroud)
例外:
java.lang.NumberFormatException: For input string: "p%"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
Run Code Online (Sandbox Code Playgroud)
我无法更改jar文件代码.只要字符串中有"%",就会执行上面的代码.
有没有办法避免异常?
该字符串没有数字,百分比字符只是问题的一部分.没有要解析的数字str(除非你试图只解析可以被视为十六进制数字的字符 - c或者a你不这样做).
您正在尝试解析字符串p%,包含字符p和%,这是不是十六进制数字.
如果要将输入字符串提供给jar,则可以通过在将输入传递给jar之前验证输入来验证相关字符是否为有效数字.你打电话给parseInt自己,如果没有得到,只能将字符串传递给jar NumberFormatException.
boolean isValid = true;
String str = "com%paq"; // this is the input string
try {
int test = Integer.parseInt( str.substring( 2, 2 + 2 ), 16 );
}
catch (NumberFormatException ex) {
isValid = false;
}
if (isValid) { // invoke the jar code
//the jar file code starts here
byte[] b = new byte[1];
b[0] = (byte)(Integer.parseInt( str.substring( 2, 2 + 2 ), 16 ) & 0xFF);
s[j++] = (new String( b, 0, 1, "ASCII" )).charAt( 0 );
}
Run Code Online (Sandbox Code Playgroud)