2018.12.15作业
解析一个邮箱地址是否合法,如果合法则打印出用户名部分和该邮箱所属的网站域名,如果邮箱地址不合法则显示不合法的原因 [选做题]
2.1 提示:邮箱地址不合法的因素:
2.1.1邮箱地址中不包含@或.
2.1.2邮箱地址中含有多了@或.
2.1.3邮箱地址中.出现在@的前面
2.1.4用户名里有其他字符
2.2实现步骤:
2.2.1创建一个类,类名:mailtest
import java.util.Scanner;
public class Zuoye4 {
public static void main(String[] args) {
System.out.println("请输入一个邮箱地址:");
Scanner input = new Scanner(System.in);
String x = input.nextLine();
if(Mail(x)==true) {
}else {
System.out.println("不合法");
}
}
public static boolean Mail(String x) {
boolean b = true;
if(x.indexOf('@')==-1||x.indexOf('.')==-1) {
System.out.println("邮箱地址不可含有@或.");
return false;
}
if(x.indexOf('@')!=x.lastIndexOf('@')||x.indexOf('.')!=x.lastIndexOf('.')) {
System.out.println("邮箱地址中多了@或.");
return false;
}
if(x.lastIndexOf('@')>x.indexOf('.')) {
System.out.println("邮箱地址中.出现在@的前面");
return false;
}
for(int i = 0;i<x.indexOf('@');i++) {
char c = x.charAt(i);
if((c>=4&&c<=57)||(c>=65&&c<=90)||(c>97&&c<=122)) {
}else {
System.out.println("邮箱用户名包含非法字符");
return false;
}
}
String[] arr = x.split("@");
System.out.println("用户名为:"+arr[0]);
System.out.println("该邮箱所属的网站域名为:"+arr[1]);
return true;
}
}