判断用户名
要求:编程检测用户名的合法性,用户名需满足以下条件:
- 长度8到20个字符
- 只能英文字母、
- 数字必须以大写字母开头
public class CheckUserName {
// 长度8到20个字符只能英文字母、数字必须以大写字母开头
public static void main(String[] args) {
System.out.println(check("Dasdasfa1") ? "合法" : "不合法");
System.out.println(check("dasdasfa1") ? "合法" : "不合法");
System.out.println(check("Dasfa1") ? "合法" : "不合法");
//三元运算符 条件 ? true(返回值) : false(返回值)
)
}
private static boolean check(String userName) {
if (!length(userName)) {
return false;
}
for (int i = 0; i < userName.length(); i++) {
char cc = userName.charAt(i);
if (!isLetter(cc) && !isnumber(cc)) {
return false;
}
if (i == 0 && !isUpperCase(cc)) {
return false;
}
}
return true;
}
private static boolean isLetter(char s) {
if (isLowerCase(s) || isUpperCase(s)) {
return true;
}
return false;
}
private static boolean isLowerCase(char s) {
if (s >= 'a' && s <= 'z') {
//加单引号 'a' 代表字母 不用转成数字
return true;
}
return false;
}
private static boolean length(String s) {
if (s.length() >= 8 && s.length() <= 20) {
return true;
}
return false;
}
private static boolean isnumber(char s) {
if (s >= '0' && s <= '9') {
return true;
}
return false;
}
private static boolean isUpperCase(char s) {
if (s >= 'A' && s <= 'Z') {
return true;
}
return false;
}
}