Core Java Fundamentals ยท Loops
Learn how to repeat a block of code as long as a specified condition is true using the while loop.
import java.util.Scanner;
public class PinEntry {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final int correctPin = 1234;
int attempts = 0;
System.out.println("Maximum attempts allowed: 3");
while (attempts < 3) {
System.out.print("Enter your PIN: ");
int enteredPin = 1111; // Simulating user input consider user inputs 1234 second time
if (enteredPin == correctPin) {
System.out.println("PIN accepted. Access granted.");
break;
} else {
System.out.println("Incorrect PIN. Please try again.");
}
attempts++;
}
if (attempts == 3) {
System.out.println("Too many incorrect attempts. Account locked.");
}
scanner.close();
}
}Scanner object is created to read user input. We will simulate this input.correctPin is declared and initialized to 1234.attempts is initialized to 0. This will track how many times the user has tried to enter the PIN.while loop condition is checked for the first time. Is attempts < 3? Since 0 < 3 is true, we enter the loop body.1111. This value is stored in the enteredPin variable.enteredPin == correctPin? Since 1111 == 1234 is false, we skip the if block.else block is executed, printing an "Incorrect PIN" message.attempts counter is incremented. Its value is now 1.while condition. Is attempts < 3? Since 1 < 3 is true, we enter the loop again.1234.enteredPin == correctPin? Since 1234 == 1234 is true, we enter the if block.break statement is executed. This immediately terminates the while loop, and execution continues on the first line after the loop.attempts == 3? Since 1 == 3 is false, this block is skipped.scanner object is closed to release system resources, and the program finishes.