public class TestException2 { public static void main(String args[]){ String str="1111.111..1.1"; try { new TestException2().isIP(str); } catch (Exception e) {
e.printStackTrace(); }
} public boolean isIP(String str) throws NotIPExption{ if(str.matches("(\\d+\\.){3}\\d+")){//就先这么简单验证一下 return true; } else{ throw new NotIPExption(); } } } class NotIPExption extends Exception{ NotIPExption(){ System.out.print("IP格式错误"); } }
楼主的需求这么奇怪?又有返回值,又说要用异常处理来完成? public static boolean isIP(String str) { String[] nums = str.split("\\."); try { if (nums.length == 4) { for (int i = 0; i < 4; i++) { int tmp = Integer.parseInt(nums[i]); if ((i == 0 && tmp == 0) || (i == 3 && tmp == 0) || tmp < 0 || tmp > 254) return false; } return true; } } catch (NumberFormatException ex) { return false; } return false; }
public class TestException2 {
public static void main(String args[]){
String str="1111.111..1.1";
try {
new TestException2().isIP(str);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isIP(String str) throws NotIPExption{
if(str.matches("(\\d+\\.){3}\\d+")){//就先这么简单验证一下
return true;
}
else{
throw new NotIPExption();
}
}
}
class NotIPExption extends Exception{
NotIPExption(){
System.out.print("IP格式错误");
}
}
public static boolean isIP(String str) {
String[] nums = str.split("\\.");
try {
if (nums.length == 4) {
for (int i = 0; i < 4; i++) {
int tmp = Integer.parseInt(nums[i]);
if ((i == 0 && tmp == 0) || (i == 3 && tmp == 0) || tmp < 0 || tmp > 254)
return false;
}
return true;
}
} catch (NumberFormatException ex) {
return false;
}
return false;
}