I'm making a program that asks you to enter a password, and adds in an option to change the password later, but every time I close it and open it again, the password is reset to the default every time I open it again. I've set the default close operation to hide, but I think every time I run the program again, it's completely new. Also, I look into the background programs of my task manager, and there's a lot of "Java TM Platform SE Binary"s.
Here's my core questions:
When I run a program from eclipse, does it open a brand new program every time? Can I change this?
How would I save variables across the open/close actions in my program?
Thanks in advance
解决方案
You didn't post any code, so I'm going to assume you have a password variable defined and your program looks something like this:
Scanner userInput = new Scanner(System.in);
String password = "Default01";
System.out.print("Enter new password: ");
password = userInput.next();
Each time you run the program, it will create in RAM, a brand new password variable instance. When the program is closed, anything in RAM is destroyed. You need some sort of persistent storage where you are writing that information to a variable. A text file is an easy way to start. Adding that would make your program look like:
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.
... Then prompt for a new password.
System.out.print("Enter new password: ");
password = userInput.next(); //prompt for new password
... Then write that new password to a file for persistent storage.
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.
Hopefully that helps a bit!