简体   繁体   English

在Java中将String转换为int并获取NumberFormatException,无法弄清原因

[英]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? 有人可以解释为什么抛出此异常吗?

int is primitive data type and it's range is : -2,147,483,648 to 2,147,483,647 int是原始数据类型,范围是-2,147,483,6482,147,483,647

6,622,015,176 is out of int range. 6,622,015,176超出int范围。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM