I'm working on a project in Java that is kind of like a digital time-machine, it basically saves what happened on a specific sate, archives it to a specific file, and stores it in a directory somewhere for safe keeping. Right now I'm working on a password function. I have the basics down for checking if it's right or wrong, but when I input the wrong answer, the class ends after saying "Invalid Password".
Is there a way to have it loop from the end of else
statement to the beginning of main
so I don't have to re-execute the class everytime?
import java.util.Scanner;
import java.util.*;
public class Adam {
public static void main(String args[]) {
String passwrd = "password";
String inputPassword;
System.out.print("Please Input Password ");
Scanner sc = new Scanner(System.in);
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
} else {
System.out.println("Invalid Password");
}
}
}
You can use a do while loop, if user input is invalid then continue the loop else not.
import java.util.Scanner;
import java.util.*;
public class Adam {
public static void main(String args[]) {
String passwrd = "password";
String inputPassword;
boolean b = true;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Please Input Password ");
inputPassword = sc.nextLine();
if (inputPassword.equals(passwrd)) {
System.out.println("Password Accepted, Loading Archive...");
b = false;
} else {
System.out.println("Invalid Password");
b = true;
}
} while (b);
}
}
DEMO
Whenever you want to run some code, check the result and then repeat if necessary the most obvious structure is do while
.
Something like the following:
String inputPassword = null;
do {
if (inputPassword != null)
System.out.println("Invalid password");
System.out.println("Enter password");
inputPassword = sc.nextLine();
} while (!inputPassword.equals(password));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With