if
statements. (Talk about fun!)Check out this code with nested if statements.
import static java.lang.System.out;
import java.util.Scanner;
public class Authenticator2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
out.print("Username: ");
String username = keyboard.next();
<strong> if (username.equals("bburd")) {</strong>
out.print("Password: ");
String password = keyboard.next();
<strong> if (password.equals("swordfish")) {</strong>
out.println("You're in.");
<strong> } else {</strong>
out.println("Incorrect password");
<strong> }</strong>
<strong> } else {</strong>
out.println("Unknown user");
<strong> }</strong>
keyboard.close();
}
}
Check out several runs of the code below. The main idea is that to log on, you have to pass two tests. (In other words, two conditions must be true.) The first condition tests for a valid username; the second condition tests for the correct password. If you pass the first test (the username test), you march right into another if
statement that performs a second test (the password test).
If you fail the first test, you never make it to the second test. Here’s the overall plan.
The code does a good job with nested if
statements, but it does a terrible job with real-world user authentication. First, never show a password in plain view (without asterisks to masquerade the password). Second, don’t handle passwords without encrypting them. Third, don’t tell the malicious user which of the two words (the username or the password) was entered incorrectly. Fourth … well, one could go on and on. The code just isn’t meant to illustrate good username/password practices.
Not enough information
message.