This project simulates an ATM user interface for PIN-code validation. It utilizes the Do-While Loop to repeatedly request input from the user until a valid four-digit positive integer (between 1000 and 9999) is provided.
The goal is to master complex range validation within post-condition loops.
Task 53: Request a PIN code until the user enters a four-digit positive number.
Requirements:
- Initialize
Scannerfor standard input. - Use a
do-whileloop to guarantee at least one prompt. - Read integer input using
scanner.nextInt(). - Set the loop condition to repeat as long as the input is outside the range 1000 to 9999.
- Print "PIN accepted." only after a valid four-digit PIN is received.
- Input Stream Management: Utilizing
java.util.Scannerfor interactive CLI. - Range Validation: Implementing a "Repeat-Until-InRange" pattern for secure input.
- Resource Control: Managing scanner lifecycle (close) to ensure memory efficiency.
- Logic Flow: The
doblock immediately displays the prompt. Afterpin = scanner.nextInt(), the conditionpin < 1000 || pin > 9999is checked. If the number is too small (e.g., 1) or too large (e.g., 10000), the loop repeats. - Condition Strategy: The logical OR (
||) ensures that any value falling outside the valid boundaries triggers another iteration. ⚠️ Clean Code Warning: This implementation assumes the user enters integers. For a production environment, one should handleInputMismatchExceptionto prevent crashes when non-numeric data is entered.
- Strict Range Enforcement: Only accepts integers with exactly 4 digits.
- Interactive Interface: Real-time communication with the user via console.
- Explicit Success Feedback: Confirms when the requirement is finally met.
Please enter your 4-digit PIN (1000-9999):
-42
Please enter your 4-digit PIN (1000-9999):
1
Please enter your 4-digit PIN (1000-9999):
10000
Please enter your 4-digit PIN (1000-9999):
1234
PIN accepted.
Project Structure:
src/com/yurii/pavlenko/
└── AtmPinValidator.java # Main Entry Point & Logic
Code
package com.yurii.pavlenko;
import java.util.Scanner;
public class AtmPinValidator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pin;
do {
System.out.println("Please enter your 4-digit PIN (1000-9999):");
pin = scanner.nextInt();
} while (pin < 1000 || pin > 9999);
System.out.println("PIN accepted.");
scanner.close();
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT