我不断从下面的代码中收到以下错误

错误:

AccountController.java:55: error: cannot find symbol
        return encoded;
               ^
  symbol:   variable encoded
  location: class AccountController
1 error


码:

public static String hash(String password) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] byteOfTextToHash = password.getBytes(StandardCharsets.UTF_8);
        byte[] hashedByetArray = digest.digest(byteOfTextToHash);
        String encoded;
        encoded = Base64.getEncoder().encodeToString(hashedByetArray);

    } catch(NoSuchAlgorithmException e) {
        e.printStackTrace();
    };
    return encoded;
}


谢谢您的帮助!

最佳答案

您的encoded变量超出范围。将其移到try之外可以解决此问题:

public static String hash(String password) {
    String encoded = null;
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] byteOfTextToHash = password.getBytes(StandardCharsets.UTF_8);
        byte[] hashedByetArray = digest.digest(byteOfTextToHash);
        encoded = Base64.getEncoder().encodeToString(hashedByetArray);

    } catch(NoSuchAlgorithmException e) {
        e.printStackTrace();
    };
    return encoded;
}

关于java - Java:无法在尝试之外返回变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60579215/

10-13 07:08