[英]How can I solve NumberFormatException when string endswith zero in Java?
I have written code to convert string into int but I'm getting error when string ends with zero '0'.我已经编写了将字符串转换为 int 的代码,但是当字符串以零“0”结尾时出现错误。
I have tried this,我试过这个,
int val=Integer.parseInt(s);
Input string,输入字符串,
9876543210
You might be trying to parse a string which does not contain a parsable integer.您可能正在尝试解析不包含可解析整数的字符串。 as document Integer.parseInt(String str) says.
正如文档Integer.parseInt(String str)所说。
Parses the string argument as a signed decimal integer.
将字符串参数解析为有符号十进制整数。 The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\-') to indicate a negative value or an ASCII plus sign '+' ('\+') to indicate a positive value.
字符串中的字符必须都是十进制数字,除了第一个字符可以是 ASCII 减号 '-' ('\-') 表示负值或 ASCII 加号 '+' ('\+')表示正值。 The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
返回结果整数值,就像参数和基数 10 作为参数提供给 parseInt(java.lang.String, int) 方法一样。
Throws: NumberFormatException - if the string does not contain a parsable integer.
抛出: NumberFormatException - 如果字符串不包含可解析的整数。
With some example we can understand it.通过一些例子我们可以理解它。
String s = "3t0";
int val=Integer.parseInt(s);
// Will throw exception
String s = "9876543210";
int val=Integer.parseInt(s);
// Will throw an Exception because 9876543210 is not an Integer see the Integer range of values (-2^31 to 2^31-1)
String s = "433"
int val=Integer.parseInt(s);
// Will successfully parse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.