题目描述:
在基于Internet的程序中,我们常常需要判断一个IP字符串的合法性。
合法的IP是这样的形式:
A.B.C.D
其中A、B、C、D均为位于[0, 255]中的整数。
为了简单起见,我们规定这四个整数中不允许有前导零存在,如001这种情况。
现在,请你来完成这个判断程序吧^_^
输入:
输入由多行组成,每行是一个字符串,输入由“End of file”结束。
字符串长度最大为30,且不含空格和不可见字符
输出:
对于每一个输入,单独输出一行
如果该字符串是合法的IP,输出Y,否则,输出N
样例输入:
1.2.3.4
a.b.c.d
267.43.64.12
12.34.56.bb
210.43.64.129
-123.4.5.6
样例输出:
Y
N
N
N
Y
N
参考解答:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String IP = sc.nextLine();
System.out.println(is_IP(IP));
}
}
private static char is_IP(String IP) {
String str[] = IP.split("\\.");
if (str.length != 4) {
System.out.println("length = " + str.length);
return 'N';
}
for (int i = 0; i < 4; i++) {
if (str[i].length() > 3) {
return 'N';
}
for (int j = 0; j < str[i].length(); j++) {
if (!Character.isDigit(str[i].charAt(j))) {
return 'N';
}
}
for (int j = 0; j < str[i].length(); j++) {
if (Integer.parseInt(str[i]) > 255) {
return 'N';
}
}
}
return 'Y';
}
}