Java输入IP,判断IP是否正确
方法一:字符判断
import java.util.Scanner;
/*
* 输入ip,判断ip是否正确
*/
public class IPJudge {
public static void main(String[] args) {
System.out.println("请输入ip地址:");
Scanner sc = new Scanner(System.in);
String strIP = sc.nextLine();
// 判断是否数字和点构成
boolean canJudge = numberPoint(strIP);
// 判断有几个点
int pointCounts = pointCounts(strIP, canJudge);
// 判断数字部分是否0-255
numberJduge(strIP, pointCounts);
sc.close();
}
private static void numberJduge(String strIP, int pointCounts) {
boolean isTrue = true;
int tempNumber[] = new int[4];
if (pointCounts == 3) {
String temp[] = strIP.split("\\.");
for (int i = 0; i < tempNumber.length; i++) {
tempNumber[i] = Integer.parseInt(temp[i]);
}
for (int j = 0; j < tempNumber.length; j++) {
if (255 < tempNumber[j] || tempNumber[j] < 0) {
isTrue = false;
break;
}
}
if (isTrue) {
System.out.println("IP格式正确:" + strIP);
} else {
System.out.println("IP格式错误!");
}
} else {
System.out.println("IP格式错误!");
}
}
private static int pointCounts(String strIP, boolean canJudge) {
int pointCounts = 0;
if (canJudge) {
for (int i = 0; i < strIP.length(); i++) {
if (strIP.charAt(i) == '.') {
pointCounts++;
}
}
}
return pointCounts;
}
private static boolean numberPoint(String strIP) {
boolean canJudge = true;
for (int i = 0; i < strIP.length(); i++) {
if (strIP.charAt(0) == '.' || strIP.charAt(strIP.length() - 1) == '.') {
canJudge = false;
break;
} else if (57 < strIP.charAt(i) || strIP.charAt(i) < 48 && strIP.charAt(i) != '.') {
canJudge = false;
break;
}
}
return canJudge;
}
}
方法二:正则表达式
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPJudge2 {
public static void main(String args[]) {
System.out.println("请输入ip地址:");
Scanner sc = new Scanner(System.in);
String strIP = sc.nextLine();
String pattern = "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(strIP);
if (m.matches()) {
System.out.println("IP格式正确:" + strIP);
} else {
System.out.println("IP格式错误!");
}
sc.close();
}
}