Skip to content

Instantly share code, notes, and snippets.

@pr4v33n
Created March 24, 2011 05:56
Show Gist options
  • Save pr4v33n/884644 to your computer and use it in GitHub Desktop.
Save pr4v33n/884644 to your computer and use it in GitHub Desktop.
deepblue
/**
* A class that models a combination lock.
*/
public class ComboLock
{
private int[] digits;
private String newCombo;
private boolean isLocked;
private int k = 0;
/**
* A combination for this lock is set when constructed.
* Although only digits are allowed, we take the entire
* string as argument.
*
* The combo lock defaults to LOCK when first created.
*/
public ComboLock(String newCombo)
{
isLocked = true;
this.newCombo = newCombo;
digits = new int[4];
}
/**
* Enter one digit at a time (as an integer). So if the combo is
* "12", calling this method twice with parameters 1 and 2 will cause it
* to UNLOCK. If the caller made a mistake, the lock will reset and
* the caller will have to enter all the digits from the beginning.
*/
public void enterDigit(int d)
{
if (d < 10) {
if (k % 4 == 0) {
digits[0] = d;
} else if (k % 4 == 1) {
digits[1] = d;
} else if (k % 4 == 2) {
digits[2] = d;
} else if (k % 4 == 3) {
digits[3] = d;
}
}
k++;
}
public void checkLock()
{
int i = 0, j = 0;
for (char c : newCombo) {
if(Character.digit(c,10) == digits[i]) {
j++;
}
i++;
}
if (j == 3) {
System.out.println("Correct!");
isLocked = false;
} else if (j != 3) {
System.out.println("Wrong! Try again.");
}
}
/**
* Checks to see if is locked or not.
*/
public boolean isLocked()
{
return isLocked;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment