0
点赞
收藏
分享

微信扫一扫

判断一个IP地址是否合法,算法面试题

王老师说 2022-02-13 阅读 95

在这里插入图片描述
在这里插入图片描述
1、 首先输入字符串,然后因为ip的特点可以根据 . 来进行分割字符串,这里需要主要分割的时候因为 . 在java里的特殊所有前面需要加上\,然后存入数组中,转换成int类型判断即可。注意输入的如果是字母转int会异常,所有用try catch处理一下,下面给出代码。

import java.util.Scanner;

public class isCorrectIp {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			String s = sc.next();
	
			if(check(s)) {
				System.out.println("Y");
			}else {
				System.out.println("N");
			}
		}
		
			
		
	}
	public static boolean check(String s) {
		String s2[] = new String[20];
		s2 = s.split("\\.");
		try {
			int a = Integer.parseInt(s2[0]);
			int b = Integer.parseInt(s2[1]);
			int c = Integer.parseInt(s2[2]);
			int d = Integer.parseInt(s2[3]);
		} catch (Exception e) {
			return false;
		}
		
		int a = Integer.parseInt(s2[0]);
		int b = Integer.parseInt(s2[1]);
		int c = Integer.parseInt(s2[2]);
		int d = Integer.parseInt(s2[3]);
		
		if(s2[0].startsWith("0")) {
			return false;
		}
		if(a>=255||a<=0) {
			return false;
		}
		if(b>=255||b<=0) {
			return false;
		}
		if(c>=255||c<=0) {
			return false;
		}
		if(d>=255||d<=0) {
			return false;
		}
		
		return true;
	}
		
}
举报

相关推荐

0 条评论