[英]Converting String to int in Java and getting a NumberFormatException, can't figure out why
ipString is a String representation of an IP address with spaces instead of dots. ipString是IP地址的字符串表示形式,带有空格而不是点。
String[] ipArray = ipString.split(" ");
String ip = "";
for (String part : ipArray){
if (part != null){
ip += part;
}
}
ip = ip.trim();
int ipInt = Integer.parseInt(ip); // Exception is thrown here.
Exception in thread "main" java.lang.NumberFormatException: For input string: " 6622015176
". 线程“主”中的异常java.lang.NumberFormatException:对于输入字符串:“
6622015176
”。 Could someone explain why this exception is being thrown? 有人可以解释为什么抛出此异常吗?
public class test {
public static void main(String args[]) {
String ipString="662 20 15 176";
String[] ipArray = ipString.split(" ");
String ip = "";
for (String part : ipArray){
if (part != null){
ip += part;
}
}
ip = ip.trim();
Long ipInt = Long.parseLong(ip);
System.out.println(""+ipInt);
}
}
6,622,015,176这个数字超出整数范围。您应该使用long而不是int,这会为您提供较大的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.