題目描述:
1、編寫一個方法驗證一個IP地址的格式是否正確,正確返回true,不正確返回false,該方法可定義如下
public boolean isRightIP(String ip)
其中,參數是要驗證的IP字符串。(注:IP地址由4部分構成,即a.b.c.d,每個部分是0~255的整數)
2、從鍵盤讀入以字符,在main方法中調用isRightIP(String ip)以測試輸入的字符串是否爲合法的IP,給出結果。
分析:題目意思是要檢測輸入的IP地址是否合法和是否正確,合不合法的標準是:輸入的只可以是數字或者“.”,若是有其他字符則是輸入不合法。檢測IP地址是否正確就是檢測IP地址的每個部分是否是0~255。public boolean ceshi (String ip)方法是檢測IP地址是否有不合法字符;public boolean chishi1(String ip)方法是檢測IP地址的“.”是否超過了三個。
代碼如下:
package ch;
import java.util.Scanner;
class judge{
public boolean isRightIP (String ip) {//檢測IP地址是否正確
String[] input=ip.split("\\.");
int a=Integer.parseInt(input[0]);//IP地址的第一個部分
int b=Integer.parseInt(input[1]);//IP地址的第二個部分
int c=Integer.parseInt(input[2]);//IP地址的第三個部分
int d=Integer.parseInt(input[3]);//IP地址的第四個部分
if(a>=0 && a<=255 && b>=0 && b<=255&& c>=0 && c<=255&&d>=0 && d<=255 )
{
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
public boolean ceshi (String ip) {//檢測IP地址是否合法
int i=ip.length();
int x=0;
for(int j=0;j<i;j++) {
if((ip.charAt(j)>47&&ip.charAt(j)<59)||ip.charAt(j)=='.'){
x++;
}
}
if(x==i)
return true;
else
return false;
}
public boolean chishi1(String ip)//檢測IP地址是否合法
{
int x=0;
int i=ip.length();
for(int j=0;j<i;j++) {
if(ip.charAt(j)==46)
x++;
}
if(x==3)
return true;
else
return false;
}
}
public class IPText{
public static void main(String [] args) {
Scanner in=new Scanner (System.in);
System.out.println("請循環輸入IP地址:");
while(in.hasNext())
{
String IP=in.nextLine();
judge ip;
ip=new judge();
boolean m=ip.ceshi(IP);
boolean n=ip.chishi1(IP);
if(m==false||n==false)
{
System.out.println("輸入有誤!請重新輸入:");
}
else
ip.isRightIP(IP);
}
}
}