Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Declare a class ComboLock that works like the combination lock
- in a gym locker, as shown here. The lock is constructed with a
- combination—
- three numbers between 0 and 39. The reset method
- resets the dial so that it points to 0. The turnLeft and turnRight
- methods turn the dial by a given number of ticks to the left or
- right. The open method attempts to open the lock. The lock opens
- if the user first turned it right to the first number in the combination,
- then left to the second, and then right to the third.
- public class ComboLock
- {
- . . .
- public ComboLock(int secret1, int secret2, int secret3) { . . . }
- public void reset() { . . . }
- public void turnLeft(int ticks) { . . . }
- public void turnRight(int ticks) { . . . }
- public boolean open() { . . . }
- }
- */
- public class Lock {
- private int[] code = new int[3];
- private int[] attempt = new int[3];
- private int[] direction = new int[3];
- private int pos;
- private int count;
- public Lock(int secret1, int secret2, int secret3) {
- code[0] = secret1;
- code[1] = secret2;
- code[2] = secret3;
- pos = 0;
- count = 0;
- }
- public void reset() {
- attempt[0] = 0;
- attempt[1] = 0;
- attempt[2] = 0;
- }
- public void turnLeft(int ticks) {
- System.out.println(pos);
- pos = pos - ticks;
- System.out.println(pos);
- if (pos >= 0) {
- attempt[count] = pos;
- } else if (pos < 0) {
- pos += 40;
- attempt[count] = pos;
- }
- direction[count] = 1;
- count++;
- }
- public void turnRight(int ticks) {
- pos = pos + ticks;
- if (pos <= 40) {
- attempt[count] = pos;
- } else {
- attempt[count] = pos - 40;
- }
- direction[count] = 0;
- count++;
- }
- public boolean open() {
- int correct = 0;
- for (int i = 0; i < 3; i++) {
- if (attempt[i] == code[i]) {
- correct++;
- }
- }
- System.out.println("------");
- for (int z : attempt) {
- System.out.println(z);
- }
- if (direction[0] == 0 && direction[1] == 1 && direction[2] == 0) {
- correct++;
- }
- if (correct == 4) {
- return true;
- } else {
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement