Java输入IP,判断IP是否正确

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();
	}

}

 

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值