Problem Description
When attempting to log into a system with forgotten credentials, systems typically impose a limit on failed attempts before account lockout. This solution implements such a password verification mechanism.
Input Specifications
The first input line contains the correct password (a non-empty string without spaces, tabs, or newlines, up to 20 characters) and a positive integer N (≤ 10) representing maximum allowed attempts. Subsequent lines contain password attempts, each terminated by a newline. Input ends when a line containing only '#' is encountered, which is not considered a password attempt.
Output Requirements
For each attempt: if correct and within attempt limit, output "Welcome in" and terminate; if incorrect, output "Wrong password: " followed by the attempt. After N failed attempts, output "Account locked" and terminate.
Java Implementation
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class PasswordValidator {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] credentials = reader.readLine().split(" ");
String correctPassword = credentials[0];
int maxAttempts = Integer.parseInt(credentials[1]);
int attemptCount = 0;
String userInput;
while ((userInput = reader.readLine()) != null) {
if (userInput.equals("#")) {
break;
}
if (attemptCount >= maxAttempts) {
System.out.println("Account locked");
return;
}
if (userInput.equals(correctPassword)) {
System.out.println("Welcome in");
return;
} else {
System.out.println("Wrong password: " + userInput);
attemptCount++;
}
}
}
}
Key Implementation Details
The solution handles two edge cases: immediate termination with '#' input with out exceeding attempt limits, and proper account lockout after exhausting all attempts. The logic ensures that password verification occurs before checking attempt limits to prevent premature lockout messages.
Test Case Examples
Input 1: Correct%pw 3
correct%pw
Correct@PW
whatisthepassword!
Correct%pw
#
Output 1:
Wrong password: correct%pw
Wrong password: Correct@PW
Wrong password: whatisthepassword!
Account locked
Input 2: cool@gplt 3
coolman@gplt
coollady@gplt
cool@gplt
try again
#
Output 2:
Wrong password: coolman@gplt
Wrong password: coollady@gplt
Welcome in