【问题标题】:How to optimize this function "checkCode" in java如何在java中优化这个函数“checkCode”
【发布时间】: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的要求,或者它已经存在于数据库中,用户必须重新输入。我正在尝试优化对我有用的第一个代码,但是当我用第二个代码替换它时,它会跳过错误并继续进行下一个输入
  • 您发布的代码与您正在运行的代码完全相同吗?我刚刚尝试运行它,两个示例的工作方式完全相同。

标签: java optional


【解决方案1】:
private static final Pattern PATTERN = Pattern.compile("^[A-Za-z0-9]{1,15}$");
private static final Predicate<String> IS_CODE_VALID = code -> PATTERN.matcher(code).matches();

public static String getNewCode(Scanner scan, Set<String> existedCodes) {
    while (true) {
        System.out.print("Enter Code: ");
        String code = scan.nextLine();

        if (existedCodes.contains(code))
            System.out.println("Code already exists in DB");
        else if (IS_CODE_NOT_VALID.test(code))
            System.out.println("Failed!! Try again!");
        else
            return code;
    }
}

【讨论】:

  • 这个答案会明显更好,并解释一下你为什么做出改变。
猜你喜欢
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2020-07-17
相关资源
最近更新 更多