1. Declare a class ComboLock that works like the combination lock in a gym locke
ID: 3604580 • Letter: 1
Question
1. Declare a class ComboLock that works like the combination lock in a gym locker. The lock is constructed with a combination—three numbers between 0 and 39. Please implement the following methods: • A constructor • A copy constructor • 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. • A toString method to show the combination code. Demonstrate the class in a complete program.
Explanation / Answer
public class ComboLock {
private int sec1;
private int sec2;
private int sec3;
private int dial;
public ComboLock (int sec1, int sec2, int sec3) {
this.sec1 = sec1;
this.sec2 = sec2;
this.sec3 = sec3;
}
public void reset() {
this.dial = 0;
}
public void turnLeft(int ticks) {
this.scroll(-ticks);
if (this.sec1 == -1) {
if (this.shouldUnlock(sec2) == true) {
System.out.println("sec 2 unlocked");
}
}
}
public void turnRight(int ticks) {
this.scroll(ticks);
if (this.shouldUnlock(sec1) == true) {
System.out.println("sec 1 unlocked");
if (this.shouldUnlock(sec2) == true) {
if (this.shouldUnlock(sec3) == true) {
System.out.println("Combo lock 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 shouldUnlock(int sec) {
if (this.dial == sec) {
sec = -1;
return true;
} else {
return false;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.