代码源自:
https://blog.csdn.net/u014259820/article/details/78833196/?ops_request_misc=&request_id=&biz_id=102&utm_term=%E9%AA%8C%E8%AF%81ip%20%E7%AE%97%E6%B3%95%20%20java&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-6-78833196.142v99control&spm=1018.2226.3001.4187
public class IsIPLegal {
public static void main(String[] args) {
// String str = "1.0.0.0";
// int a = Integer.parseInt(str); //int
// int b = Integer.valueOf(str); // Integer
// System.out.println(b);
// 原始的int数据类型,则使用Integer.parseInt()方法。
// 包装类对象,则使用valueOf()方法。
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
boolean istrue = isIPLegal(str);
System.out.println(istrue);
// nextLine输入的字符串可以含有空格,以回车结束
// next输入的字符串不能含有空格,以空格、tab、回车结束
}
private static boolean isIPLegal(String str) {
//1、非空
if (str == null) {
return false;
}
//2、整个字符串长度---7-15
if (str.length() < 7 || str.length() > 15) {
return false;
}
//3、分割,小于=4段
String[] arr = str.split("\\.");
if (arr.length != 4) {
return false;
}
//4、每个字符都是数字--遍历
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length(); j++) {
if (arr[i].charAt(j) < '0' || arr[i].charAt(j) > '9') {
return false;
}
}
}
//5、每段作为数字,0-255范围内
for (int i = 0; i < arr.length; i++) {
int temp = Integer.parseInt(arr[i]);
//第一段1-255
if (i == 0) {
if (temp < 1 || temp > 255) {
return false;
}
//2-3段0-255
} else {
if (temp < 0 || temp > 255) {
return false;
}
}
}
//6、都没校验到,返回true
return true;
}
}