java实现--编写一个方法验证一个IP地址的格式是否正确

题目:

1、编写一个方法验证一个IP地址的格式是否正确,正确返回true,不正确返回false,该方法可定义如下

public boolean isRightIP(String ip)

其中,参数是要验证的IP字符串。(注:IP地址由4部分构成,即a.b.c.d,每个部分是0~255的整数)

2、从键盘读入以字符,在main方法中调用isRightIP(String ip)以测试输入的字符串是否为合法的IP,给出结果。


import java.util.*;
public class ex_3_1 {
	public static boolean isRightIP(String ip) {
		int index,a1,b1;
		boolean bool=true;
		for(int i=1;i<=3;i++) {
			index = ip.indexOf('.');
			a1=Integer.parseInt(ip.substring(0, index));
			if(a1<0||a1>255) {
				bool=false;
				break;
			}
			if(i!=3) 
				ip=ip.substring(index+1);
			else {
				ip=ip.substring(index+1);
				b1=Integer.parseInt(ip.substring(0));
				if(b1<0||b1>255) 
					bool=false;
			}
		}
		return bool;
	}
	public static void main(String[] args) {
		Scanner read=new Scanner(System.in);
		String a;
		boolean Bool;
		a=read.next();
		Bool=ex_3_1.isRightIP(a);
		System.out.println("IP地址合法性:"+Bool);
	}
}

 

 

 

 

你可能感兴趣的:(java练习)