编写程序完成,对录入信息进行有效性验证
需求说明:
录入会员生日时,形式必须是“月/日”,如“09/12”;录入的密码必须在6~10位之间;允许用户重复录入,直到输入正确为止。
public static String check(String birth, String pwd) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd");
try {
Date parse = dateFormat.parse(birth);
} catch (ParseException ignored) {
return "生日格式错误";
}
if (pwd != null) {
if (pwd.length() < 6 || pwd.length() > 10) {
return "密码长度错误";
}
}
return null;
}
傻瓜式写法:
public static boolean isvalid(String str){
if(str.length() != 5)
return false;
//判断年月
if(str.charAt(0) < '0' || str.charAt(0) > '9')
return false;
if(str.charAt(1) < '0' || str.charAt(1) > '9')
return false;
if(str.charAt(2) != '/')
return false;
if(str.charAt(3) < '0' || str.charAt(0) > '9')
return false;
if(str.charAt(4) < '0' || str.charAt(0) > '9')
return false;
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int flag = 1;
while(flag > 0){
System.out.println("请输入生日(月/日)");
String str = sc.next();
if(isvalid(str))
break;
}
while( flag > 0){
System.out.println("请输入密码");
String pwd = sc.next();
if(pwd.length() >= 6 && pwd.length() <= 10)
break;
}
}
public static void main(String args[]) {
String str = "";
String pattern = "1\d\/[0-3][0-9]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
System.out.println(m.matches());
}
public static void main(String args[]) {
String str = "";
String pattern = "[0-9]{6,9}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
System.out.println(m.matches());
}