我正在尝试使用扫描仪将 IP 地址(字符串)分成 4 个整数。我使用了分隔符并将模式设置为“。”
next() 文档:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
我最初尝试使用末尾没有句点的 IP 字符串,但现在我尝试在字符串的每个末尾添加句点。扫描仪 next() 仍然不扫描我的号码(或任何东西)。
public void setIP(String ip){
IPstring = "."+ip+".";
Scanner sc = new Scanner(IPstring);
sc.useDelimiter(".");
System.out.println(IPstring);
System.out.println(sc.next());
System.out.println(sc.next());
System.out.println(sc.next());
sc.close();
}
输出:
.216.198.240.0.
注意:.216.198.240.0下有3个空行。
我打算将 println 替换为:
IP1 = Integer.parseInt(sc.next());
IP2 = Integer.parseInt(sc.next());
IP3 = Integer.parseInt(sc.next());
IP4 = Integer.parseInt(sc.next());
IP1-4 是代表 IP 地址的 4 个部分的整数。
最佳答案
关于Java Scanner next() 扫描空 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50108698/