用一下正则表达式过滤一下非数字字符、空串、和“.”不是4个的情况,再判断是不是其中的数是不是0-255。
注意过滤“01”这种0在开头的不合法情况。
做字符串的题还是要会点正则表达式的,很多题做起来会方便很多。
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String s = in.nextLine();
            String out = "YES";
            if(!s.matches("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+")){
                out="NO";
            }else{
                String[] ip = s.split("\\.");
                for(int i=0;i<4;i++){
                    if(Integer.parseInt(ip[i])  < 0 || Integer.parseInt(ip[i]) > 255 || (ip[i].charAt(0) == '0' && ip[i].length() != 1)){
                        out="NO";
                    }
                }
            }
            System.out.print(out);
        }
    }