【发布时间】:2019-04-06 11:57:26
【问题描述】:
我有这段代码在java中调用函数检查有效代码
do {
System.out.print("Enter Code: ");
infor.setCode(sc.nextLine());
if (check.checkCode(infor.getCode()) == true) {
boolean aa = true;
for (int i = 0; i < list.size(); i++) {
if (infor.getCode().equals(list.get(i).getCode())) {
aa = false;
System.out.println("Code already exists in DB");
break;
}
}
if (aa) {
break;
} else {
continue;
}
}
System.out.println("Failed!! Try again!");
} while (true);
我正在尝试优化此代码:
boolean aa;
do {
aa = true;
System.out.print("Enter Code: ");
infor.setCode(sc.nextLine());
if (check.checkCode(infor.getCode()) == true) {
for (int i = 0; i < list.size(); i++) {
if (infor.getCode().equals(list.get(i).getCode())) {
aa = false;
System.out.println("Code already exists in DB");
break;
}
}
}
System.out.println("Failed!! Try again!");
} while (aa == false);
但它不能返回不符合要求功能的输入,也不允许我重新输入。有什么解决办法吗?
public boolean checkCode(String input){
String regex = "^[A-Za-z0-9]{1,15}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
【问题讨论】:
-
我不完全确定问题出在哪里 - 你能详细说明“无法返回输入”吗?我看不到您试图在“之前”或“之后”代码中返回输入的位置。这是您遇到的错误,还是此处未显示实际问题的代码?
-
我的do while循环要求用户输入代码,如果它不符合函数checkCode的要求,或者它已经存在于数据库中,用户必须重新输入。我正在尝试优化对我有用的第一个代码,但是当我用第二个代码替换它时,它会跳过错误并继续进行下一个输入
-
您发布的代码与您正在运行的代码完全相同吗?我刚刚尝试运行它,两个示例的工作方式完全相同。