Java Integer.parseInt()不适用于大数字

Oli*_*ryn 2 java static-methods integer class parseint

我有以下简单的代码片段,用于检测给定的IPv4地址确实只有数值(即在剥离点后):

import edu.gcc.processing.exceptions.net.IPAddressNumericException;

//Get the IP address
  String address = "239.255.255.255";

//Check to see if this is a number      
  try {
    String IPNumbers = address.replace(".", "");
    Integer.parseInt(IPNumbers);            
  } catch (NumberFormatException e) {
    System.out.print(e.getMessage());
  }
Run Code Online (Sandbox Code Playgroud)

由于某种原因,NumberFormatException被解雇了,我得到这个错误:

For input string: "239255255255"
Run Code Online (Sandbox Code Playgroud)

有人可以帮我理解这个吗?该parseInt()方法适用于较小的数字,例如127001.

感谢您的时间.

PTB*_*TBG 8

尝试使用 Long.parseLong(IPNumbers)


Dav*_*ton 7

为什么不使用正则表达式,或使用split(".")?将其分解为其组件?

除了需要仅由数字组成之外,还有其他限制.例如:

666.666.666.666
Run Code Online (Sandbox Code Playgroud)

这将解析得很好,但是......不太可能是IP.

将其分解为其部分可以让您确定(a)它有四个部分,以及(b)每个部分在IP地址的上下文中实际上是有意义的.

您也可以使用InetAddress实现,或者InetAddressValidator使用Apache Commons.


Rio*_*ams 5

对于非常大的整数,您可能需要使用BigInteger类(BigDecimal,因为这些值可能会超出 Integer 的限制。

整数限制:

Minimum : -2147483648
Maximum :  2147483647
Run Code Online (Sandbox Code Playgroud)

使用大整数:

string s = "239255255255";
BigInteger yourNumber = new BigInteger(s);
Run Code Online (Sandbox Code Playgroud)