一个简易的注册程序
要求
用户名长度3-10之间
密码只能是小写字母
邮箱必须有@ 和. 且都不能出现在开头和结尾的位置 长度最短6
代码
import java.util.Scanner;
public class UserRegister {
String name = null;
String PSW = null;
String email = null;
public void scanner() {
Scanner scannerName = new Scanner(System.in);
System.out.println("请输入你的用户名:");
if (scannerName.hasNext()) {
this.name = scannerName.next();
}
System.out.println("请输入你的密码:");
Scanner scannerPSW = new Scanner(System.in);
if (scannerPSW.hasNext()) {
this.PSW = scannerPSW.next();
}
System.out.println("请输入你的邮箱地址:");
Scanner scannerEmail = new Scanner(System.in);
if (scannerEmail.hasNext()) {
this.email = scannerEmail.next();
}
}
public void test() {
//过三关判断,抛出异常
//第一关 名字长度3-10之间
//处理方法都是写出正确的情况,然后取非抛出异常!!!
if (!(this.name.length() > 2 && this.name.length() < 10)) {
throw new RuntimeException("用户名长度应在3-10之间");
}
//第二关 密码只能是小写字母 个数不能小于6
// 需要把String-->char[]
if (!(change() && this.PSW.length() >= 6 )){
throw new RuntimeException("密码格式错误,长度至少为6,且只能是小写字母");
}
//第三关 邮箱必须有@ 和. 且都不能出现在开头和结尾的位置 长度最短6
if (!(this.email.length()>=6 && index())){
throw new RuntimeException("邮箱格式错误");
}
}
public boolean change() {
char[] chars = this.PSW.toCharArray();//用到String的方法toCharArray
for (int i = 0; i < this.PSW.length(); i++) {
if (!(chars[i] >= 'a' && chars[i] <= 'z')) {
return false; //有异常
}
}
return true;//无异常
}
public boolean index(){
int i = this.email.lastIndexOf(".");
int j = this.email.lastIndexOf("@");
int q = this.email.indexOf("@");
int p = this.email.indexOf(".");
if ( i>j && q > 0 && p > 0 ){
return true;
}else {return false;}
}
}
//
public class Application {
public static void main(String[] args) {
UserRegister userRegister = new UserRegister();
userRegister.scanner();
try {
userRegister.test();
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
System.out.println("恭喜你注册成功!");
}
}