JAVA--email校验练习

1.用户从控制台输入姓名和email,判断用户输入的email是否符合规则(记住异常处理),

以及是否为新浪地址以名字lisi开头,sina.com结尾(lisi@sina.com)

2.只有1个@和 . 且@和 . 不能相邻

3.@在 . 之前,且 . 不能是最后最后一位

4.判断email是否为新浪email

5.输出结果

---------------------------------------

 User类(使用了lombok插件)

import lombok.*;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {

private String name;
private String email;
}
-----------------------------------------------------------
Demo02类
public class Demo02 {
private static User user;

public static void main(String[] args) {
demo01(user);
}

private static void demo01(User user) {
System.out.println("-------------邮箱注册--------------");
Scanner input = new Scanner(System.in);
System.out.println("请输入用户名");
String name = input.next();
if (name == null) {
System.out.println("用户名为空");
return;
}
String answer = null;
String email = null;
do {
System.out.println("请输入邮箱地址");
email = input.next();
String emailRegex = "([\\w])*@([A-Za-z\\d]){2,}\\.([a-z]){2,}";
boolean matches = email.matches(emailRegex);
try {
if (!matches) {
email = null;
throw new RuntimeException("输入邮箱格式不正确,请重新录入");
} else System.out.println("邮箱格式正确");
break;
} catch (RuntimeException e) {
e.printStackTrace();
}
System.out.println("是否重新录入:y/n");
answer = input.next();
} while ("y".equals(answer));

if (email == null) {
System.out.println("邮箱注册失败");
return;
}
if ((email.endsWith("sina.com")) && (email.startsWith(name))) {
System.out.println(name + "注册新浪邮箱成功,email:" + email);
} else {
System.out.println(name + "注册成功,email:" + email);
}
input.close();
}
}


posted @ 2022-10-19 15:56  学JAVA的旅行者  阅读(122)  评论(0)    收藏  举报