题目:判断传入的字符串是否为ip地址
/**
* 判断传入的字符串是否为ip地址
* @param ip
* @return
* @throws Exception
*/
public static boolean isIP(String ip) throws Exception {
boolean isTrue=false;
ip = ip.replace(" ", "");//去除空格
String[] arr=ip.split("\\.");//根据“.”将字符串分割
if(arr.length==4) {
for (int i = 0; i < 4; i++) {
if(isInt(arr[i])==false) {
throw new Exception("【"+ip+"】"+"第"+(i+1)+"个部分不是数字");
}
int temNum=toInt(arr[i]);
if(temNum>255||temNum<0) {
throw new Exception("【"+ip+"】"+"第"+(i+1)+"个部分数字超出范围") ;
}
}
isTrue=true;
}else {
throw new Exception("【"+ip+"】不是四个区段,应该形如127.0.0.1");
}
return isTrue;
}
/**
* 判断字符串是否为纯数字(int类型),返回布尔类型值
* @param pstr
* @return
*/
public static boolean isInt(String pstr){
boolean isOk=false;
try {
int tem=Integer.parseInt(pstr);
isOk=true;
}catch(Exception e){
}
return isOk;
}
/**
* 转换字符串为纯数字(int类型),返回转换后的数字
* 异常则返回数字0
* @param pstr
* @return
*/
public static int toInt(String pstr){
int tem;
try {
tem=Integer.parseInt(pstr);
}catch(Exception e){
tem=0;
}
return tem;
}