Core Java Fundamentals ยท Loops

While Loop

Learn how to repeat a block of code as long as a specified condition is true using the while loop.

PinEntry.java

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();
    }
}

Step by step

  1. The program starts. A Scanner object is created to read user input. We will simulate this input.
  2. A constant correctPin is declared and initialized to 1234.
  3. A counter variable attempts is initialized to 0. This will track how many times the user has tried to enter the PIN.
  4. An informational message is printed to the console. The string is added to the string pool.
  5. The while loop condition is checked for the first time. Is attempts < 3? Since 0 < 3 is true, we enter the loop body.
  6. The program prompts the user to enter their PIN.
  7. We simulate the user entering an incorrect PIN, 1111. This value is stored in the enteredPin variable.
  8. The entered PIN is checked. Is enteredPin == correctPin? Since 1111 == 1234 is false, we skip the if block.
  9. The else block is executed, printing an "Incorrect PIN" message.
  10. The attempts counter is incremented. Its value is now 1.
  11. End of the first iteration. The execution jumps back to the while condition. Is attempts < 3? Since 1 < 3 is true, we enter the loop again.
  12. This time, let's simulate the user entering the correct PIN, 1234.
  13. The PIN is checked again. Is enteredPin == correctPin? Since 1234 == 1234 is true, we enter the if block.
  14. A success message is printed.
  15. The break statement is executed. This immediately terminates the while loop, and execution continues on the first line after the loop.
  16. Execution has jumped past the loop. Now we check if the user ran out of attempts. Is attempts == 3? Since 1 == 3 is false, this block is skipped.
  17. The scanner object is closed to release system resources, and the program finishes.