“`” 参考回答:

IP的格式:(1~255).(0~255).(0~255).(0~255)

方法一:基于对字符串的处理

public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String ipStr = scanner.next();
boolean isIpLegal = isIpLegal(ipStr);
if(isIpLegal) {
System.out.println(ipStr + "" 合法"");

}

else{

System.out.println(ipStr + "" 非法"");

}

}

public static boolean isIpLegal(String str){

//检查ip是否为空

if(str == null){

return false;

}

//检查ip长度,最短为:x.x.x.x(7位),最长为:xxx.xxx.xxx.xxx(15位)

if(str.length() < 7 || str.length() > 15){

return false;

}

//对输入字符串的首末字符判断,如果是"".""则是非法IP

if(str.charAt(0) == '.' || str.charAt(str.length()-1) == '.'){

return false;

}

//按"".""分割字符串,并判断分割出来的个数,如果不是4个,则是非法IP

    String[] arr = str.split(""\\."");
    if(arr.length != 4){
    return false;
    }
    
    
//对分割出来的每个字符串进行单独判断

for(int i = 0; i < arr.length; i++){

//如果每个字符串不是一位字符,且以'0'开头,则是非法的IP,如:01.002.03.004

if(arr[i].length() > 1 && arr[i].charAt(0) == '0'){

return false;

}
//对每个字符串的每个字符进行逐一判断,如果不是数字0-9,则是非法的IP
for(int j = 0; j < arr[i].length(); j++){
if (arr[i].charAt(j) < '0' || arr[i].charAt(j) > '9'){
return false;
}
}
}

//对拆分的每一个字符串进行转换成数字,并判断是否在0~255

    for(int i = 0; i < arr.length; i++){
    int temp = Integer.parseInt(arr[i]);
    if(i == 0){
    if (temp < 1 || temp > 255){
    return false;
    }
    }
    else{
    if(temp < 0 || temp > 255){
    return false;
    }
    }
    }
    return true;
    }

 

方法二:正则表达式

public static` `void` `main(String[] args) {``Scanner scanner = ``new` `Scanner(System.in);``String ipStr = scanner.next();``boolean isIpLegal = isIpLegal(ipStr);``if``(isIpLegal) {`
System.out.println(ipStr + "" 合法"");

}
else{
System.out.println(ipStr + "" 非法"");
}
}

public static boolean isIpLegal(String ipStr) {
   String ipRegEx = ""^([1-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))(\\.([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))){3}$"";
  Pattern pattern = Pattern.compile(ipRegEx);
  Matcher matcher = pattern.matcher(ipStr);
  if (matcher.matches()) {
   return true;
  } 
    else {
        return false;
    }
}

 

 

测试用例:

等价类划分:

有效可用的IP地址  
A类 1.0.0.0 -126.255.255.254
A私有 10.0.0.0 -10.255.255.254
B类 128.0.0.0 -191.255.255.254
B私有 172.16.0.0 -172.31.255.254
C类 192.0.0.0 -223.255.255.254
C私有 192.168.0.0-192.168.255.254
windows自动分配 169.254.0.0-169.254.255.254
有效但不可用的IP地址  
D 224.0.0.0 -239.255.255.254
E 240.0.0.0 -255.255.255.254
全网 0.x.x.x, x.x.x.0
广播 x.x.x.255

回环127.0.0.0 -127.255.255.254
输入结果64.11.22.33有效可用10.12.13.14有效可用,不能直接访问公网151.123.234.56有效可用172.20.123.56有效可用,不能直接访问公网192.127.35.65有效可用192.168.128.128有效可用,不能直接访问公网169.254.15.200有效可用,不能直接访问公网224.1.2.3有效不可用,超过有效范围(D类)250.11.22.33有效不可用,超过有效范围(E类)0.200.3.4有效不可用,全网地址64.11.22.0有效不可用,全网地址10.12.13.255有效不可用,广播地址127.50.60.70有效不可用,回环地址

            "```

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.