public class Demo59 {
public static void main(String[] args) {
try {
System.out.println(new EmailRegistration("Amy", "123456", "Amy@home.com"));
} catch (RuntimeException e) {
System.out.println(e.getMessage()+"\t注册失败!");
}
}
public static class EmailRegistration{
private String username,passwd,emailAddress;
public EmailRegistration(String username, String passwd, String emailAddress) {
if(username.length()>=2 && username.length()<=4) {//用户名的长度校验
this.username = username;
if (passwd.length() ==6 && isDigital(passwd)) {//密码长度为6同时都是数字
this.passwd = passwd;
if(emailAddress.contains("@") && emailAddress.contains(".") //邮箱必须包含@和.
&& emailAddress.lastIndexOf("@")>0 //@不能放在最前面
&& emailAddress.lastIndexOf(".")!= emailAddress.length()-1 //.不能放在最後面
&& emailAddress.indexOf("@") == emailAddress.lastIndexOf("@") //@不能重复出现
&& emailAddress.indexOf(".") == emailAddress.lastIndexOf(".") //.不能重复出现
&& emailAddress.indexOf("@") < emailAddress.indexOf(".")) { //@要在.的前面
this.emailAddress = emailAddress;
toString();}
else {
throw new RuntimeException("邮箱不合法");
}
}
else throw new RuntimeException("您输入的密码格式不正确");
}
else throw new RuntimeException("您输入的用户名不正确");
}
@Override
public String toString() {
return "您已成功注册!" +
"用户名:" + username + '\t'+
"密码: ******" + '\t' +
"邮箱地址:" + emailAddress;
}
public boolean isDigital(String passwd){
try {
Integer.parseInt(passwd);//如果成功转换成整型就表示全都是数字
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
}
Java异常处理与String应用
于 2023-02-28 15:35:20 首次发布