你沒有張貼任何代碼,所以我會假設你有一個password
變量定義和你的程序看起來是這樣的:
Scanner userInput = new Scanner(System.in);
String password = "Default01";
System.out.print("Enter new password: ");
password = userInput.next();
每次運行程序時,它會創建在RAM中,一個全新的password
變量實例。當程序關閉時,RAM中的任何內容都將被銷燬。您需要某種持久性存儲,將這些信息寫入變量。一個文本文件是一個簡單的方法來開始。添加這將使您的程序看起來像:
Scanner userInput = new Scanner(System.in);
File passwordFile = new File("passwordfile.txt");
//this is where the password is stored.
Scanner passwordScanner = new Scanner(passwordFile);
//this is how you read the file.
String password = passwordScanner.next();
//password has been read.
...然後提示輸入新密碼。
System.out.print("Enter new password: ");
password = userInput.next(); //prompt for new password
...然後將該新密碼寫入文件進行永久存儲。
PrintWriter passwordWriter = new PrintWriter("passwordfile.txt");
// overwrites the current passwordfile.txt, so you now have an empty file
passwordWriter.print(password);
//writes the password to passwordfile.txt so it can be used next time.
希望這會有所幫助!