思路解读--
利用try catch抓住异常并返回异常信息并输出
过关斩将思想
一层一层的去判断条件是否符合
如果有异常直接抛出异常
在主方法中抓住异常并输出错误信息
代码如下:
/**
* @author 徐云鹏
* 仅供学习交流!
*/
public class Test {
/**
* 输入用户名,密码,邮箱,如果信息录入正确,则提示注册成功,否则生成异常对象
* 1.用户名的长度在2-4之间
* 2.密码的长度为6,并且全部为数字
* 3.邮箱中包含@ 和 . 并且 @ 在 . 的前面
*/
public static void main(String[] args) {
//主方法调用userInfo并 try catch
try {
userInfo("小北", "123456", "141@qq.com");
System.out.println("注册成功!");
} catch (Exception e) {
//这里抓住异常,但是别继续抛出,继续抛出程序就崩了
//直接输出异常信息即可 不影响程序进程
System.out.println(e.getMessage());
}
}
public static void userInfo(String username, String password, String email) {
//根据每一条件进行判断,只要不通过,就抛出异常
//即正确条件取反,进入 抛出异常
//用户名判断
if (!(username.length() >= 2 && username.length() <= 4)) {
throw new RuntimeException("用户名格式不正确...");
}
//密码判断 我们写一个方法去调用,这个方法去判断是否为数字 返回一个Boolean值
if (!(password.length() == 6 && passwordRes(password))) {
throw new RuntimeException("密码格式不正确...");
}
//邮箱判断
//先确定@ 和 . 的位置
int i = email.indexOf("@");
int j = email.indexOf(".");
//i > 0代表@前不能为空 ,j > i代表. 必须在@后面
if (!(i > 0 && j > i)) {
throw new RuntimeException("邮箱格式不正确...");
}
}
//判断密码是否为数字的方法
//先转换为字符数组,遍历数组,如果阿斯克码小于0或大于9就不是一个数字,就返回false 否则返回true
public static boolean passwordRes(String str) {
char arr[] = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] < '0' || arr[i] > '9') {
return false;
}
}
return true;
}
}