String Replace not working as I think it should [d

2020-05-10 08:46发布

public static boolean passwordConfirmed() {
    String attempt = JOptionPane.showInputDialog("Password: ");
    FileReader fstream = null;
    String password = "";
    try {

        fstream = new FileReader("pass.txt");
        BufferedReader in = new BufferedReader(fstream);

        password = in.readLine();
        password.replace("Password: ", " ");

        System.out.println(password);

    } catch (IOException e) {
        e.printStackTrace();
    }

    if (attempt.equals(password)) {
        System.out.print("True");
        return true; 
    } else System.out.println("false");
    return false;
}

Trying to remove "Password: " from the line. It gets the line "Password: " + text afterwards (Password) I want to remove the "Password: ", so all i have left is purely the text afterwards.

1条回答
forever°为你锁心
2楼-- · 2020-05-10 09:20

Always re-assign it.

password = password.replace("Password: ", " ");

Strings are immutable in Java, meaning you can't modify an existing instance of it. By re-assigning it, you'll be capturing the new value of the string into an existing variable.

查看更多
登录 后发表回答