用split函数将ip地址按 . 分隔
判断若超过四段则不是,开头有0则不是
将string类的字符转换成int类型的ASCII码,若大于57或小于48说明不是数字
把他们加起来判断是否在[0, 255]间
import java.util.*;
public class Main {
static String s;
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
s = in.nextLine();
check(s);
}
}
public static void check(String s) {
String[] str = s.split("\\.");
if(str.length != 4) {
System.out.print("N");
return;
}
for(int i = 0 ; i < 4 ; ++ i) {
if(str[i].length() > 3) {
System.out.print("N");
return;
}
if(str[i].charAt(0) == '0') {
System.out.print("N");
return;
}
int a, total = 0;
for(int j = 0 ; j < str[i].length() ; ++ j) {
a = str[i].charAt(j);
if(a < 48 || a > 57) {
System.out.print("N");
return;
}
total *= 10;
total += a;
total -=48;
}
if(total > 255 || total < 0) {
System.out.print("N");
return;
}
}
System.out.println("Y");
}
}