In: Computer Science
In.java
Write a program that repeatedly asks the user to enter their
password until they enter the correct one. However, after 5 failed
attempts, the program "locks out" the user. We will show that with
an error message.
Assume the password is HOC2141 (case
sensitive).
Note that there is a special case that is not shown below. To
identify it, think of all possible scenarios of input for this
program.
----------- Sample run 1: Enter your password: Blake Wrong Enter your password: hoc2341 Wrong Enter your password: hoc2141 Wrong Enter your password: HOC2141 Correct! You're in! Bye ----------- Sample run 2: Enter your password: HOC2141 Correct! You're in! Bye ----------- Sample run 3: Enter your password: asdf Wrong Enter your password: ffgdf Wrong Enter your password: asdxcv Wrong Enter your password: 1276 Wrong Enter your password: HOCK Wrong You are locked out! Bye
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// Login.java
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
// storing original password
String password = "HOC2141";
// scanner for input
Scanner scanner = new Scanner(System.in);
String userInput;
int attempts = 0;
boolean in = false;
// looping until 5 attempts are exhausted or user enter it correctly
while (attempts < 5) {
// asking and reading password
System.out.print("Enter your password: ");
userInput = scanner.nextLine();
// comparing password with original
if (userInput.equals(password)) {
// success
System.out.println("Correct! You're in!");
in = true;
break; // exiting loop
} else {
// wrong
System.out.println("Wrong");
}
// incrementing number of attempts
attempts++;
}
// if in is not true, and the loop is over, printing 'You are locked
// out!'
if (!in) {
System.out.println("You are locked out!");
}
System.out.println("Bye");
}
}
/*OUTPUT 1*/
Enter your password: hdjsd
Wrong
Enter your password: HOC2141
Correct! You're in!
Bye
/*OUTPUT 2*/
Enter your password: hoc2141
Wrong
Enter your password: hOC2141
Wrong
Enter your password: HOC2141
Correct! You're in!
Bye
/*OUTPUT 3*/
Enter your password: hsjks
Wrong
Enter your password: jhfjk
Wrong
Enter your password: whuw
Wrong
Enter your password: sdh
Wrong
Enter your password: wduwhdj
Wrong
You are locked out!
Bye