THINK FIRST·CODE LATER

← All labs

A PIN lock that blocks after three mistakes

Problem

Write a class PinLock and a public class PinLockApp. A lock has a private PIN, a count of failed attempts and an open/closed state. No method ever returns the PIN.

method behaviour
boolean unlock(String code) opens with the right code and resets the failures; a wrong code counts one failure; after MAX_ATTEMPTS = 3 failures the lock is blocked and refuses everything
void lock() closes the lock
boolean changePin(String newPin) only while open, and only for exactly 4 digits
isOpen(), isBlocked(), attemptsLeft() queries
toString() OPEN, BLOCKED or LOCKED (2 attempts left)

main reads the initial PIN, then commands try CODE, lock, change CODE until the end of input.

For the input

1234 try 1111 try 1234 change 99 change 4321 lock try 1234 try 4321

the program prints

try 1111: refused -> LOCKED (2 attempts left)
try 1234: opened -> OPEN
change 99: refused -> OPEN
change 4321: done -> OPEN
lock -> LOCKED (3 attempts left)
try 1234: refused -> LOCKED (2 attempts left)
try 4321: opened -> OPEN

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l10-5-data-1.txt

1234 try 1111 try 1234 change 99 change 4321 lock try 1234 try 4321
What your program must print for l10-5-data-1.txt
try 1111: refused -> LOCKED (2 attempts left)
try 1234: opened -> OPEN
change 99: refused -> OPEN
change 4321: done -> OPEN
lock -> LOCKED (3 attempts left)
try 1234: refused -> LOCKED (2 attempts left)
try 4321: opened -> OPEN

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l10-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content l10-5-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.