ComboLock Declare a class ComboLock that Works like the combination lock in a gy
ID: 670534 • Letter: C
Question
ComboLock Declare a class ComboLock that Works like the combination lock in a gym locker. The lock is constructed with a combination- tliree 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 secretl , int secret2 , int secret3) {. . . } public void reset () { . . . } public void turnLeft (int ticks) { . . . } public void turnRight (int ticks) { . . . } public boolean open ( ) { . . . } }Explanation / Answer
//import java.io.*;
public class ComboLock {
int secret1,secret2,secret3,dial;
public ComboLock(int secret1, int secret2, int secret3) {
this.secret1 = secret1;
this.secret2 = secret2;
this.secret3 = secret3;
}
public void reset() {
this.dial = 0;// reset to zero
}
public void turnLeft(int ticks) {
this.scroll(ticks);
if (this.secret1 == 1) {
if (this.open(secret2) == true) {
System.out.println("The Secret2 num is unlocked");
}
}
}
public void turnRight(int ticks) {
this.scroll(ticks);
if (this.open(secret1) == true) {
System.out.println("Secret 1 unlocked");
if (this.open(secret2) == true) {
if (this.open(secret3) == true) {
System.out.println("Combo lock is unlocked");
}
}
}
}
public void scroll(int ticks) {
if (this.dial + ticks > 39) {
if (ticks >= 39) {
this.dial += ticks - 39;
} else if (this.dial >= 39) {
}
} else if (this.dial + ticks < 0) {
this.dial += 40 + ticks;
this.dial += ticks - 40;
} else {
this.dial += ticks;
}
}
public boolean open(int secret) {
if (this.dial == secret) {
secret = -1;
return true;
} else {
return false;
}
}
public static void main(String args[]){
ComboLock cl= new ComboLock(2,3,4);
cl.turnLeft(2); // give input int type
cl.turnRight(2);
cl.scroll(2);
cl.open(2);
}
}