題目描述
現在IPV4下用一個32位無符號整數來表示,一般用點分方式來顯示,點將IP地址分成4個部分,每個部分爲8位,表示成一個無符號整數(因此不需要用正號出現),如10.137.17.1,是我們非常熟悉的IP地址,一個IP地址串中沒有空格出現(因爲要表示成一個32數字)。
現在需要你用程序來判斷IP是否合法。
輸入描述:
輸入一個ip地址
輸出描述:
返回判斷的結果YES or NO
輸入例子:
10.138.15.1
輸出例子:
YES
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
while(scan.hasNext())
{
if(YesOrNo(scan.nextLine()))
System.out.println("YES");
else
System.out.println("NO");
}
}
static boolean YesOrNo(String str)
{ //首先判斷是否包含了除數字和.之外的字符,如果包含了直接判定非法
for(char ch:str.toCharArray()){
if(ch>'9'&&ch!='.' || ch<'0'&&ch!='.')
return false;
}
String[] strs=str.split("\\.");
if(strs.length!=4)//如果長度不爲4,直接判定非法
return false;
else{
for(int i=0;i<4;i++){//如果有數字的範圍不在0~255之間,判定非法
if(!(Integer.parseInt(strs[i])>=0 && Integer.parseInt(strs[i])<=255)){
return false;
}
}
return true;
}
}
}