In: Computer Science
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() { . . . }
}
In Class P8_1’s main method, test the operation of the lock by showing one Successful case of opening the lock and one Unsuccessful case of opening the lock given a wrong order. To do so, instantiate a ComboLock object and provide the 3 secrets to the constructor and use the ComboLock methods to turn the lock left/right and attempt to open the lock.
Code to copy:
//let comboCode is 171229
import java.util.*;
public class ComboLock {
int key_1,key_2,key_3;
public ComboLock()
{
key_1=0;
key_2=0;
key_3=0;
}
public ComboLock(int secrt_1, int
secrt_2, int secrt_3) {
key_1 =
secrt_1;
key_2 =
secrt_2;
key_3 =
secrt_3;
}
public static boolean turnLeft(int
num_Of_tickes) {
if(num_Of_tickes
== 1 || num_Of_tickes == 3)
return true;
return
false;
}
public static boolean turnRight(int
num_Of_tickes) {
if(num_Of_tickes
== 2)
return true;
return
false;
}
public static boolean open()
{
System.out.println("Your Combolock is open");
return
true;
}
public static boolean menu_list(int
a,int s)
{
Scanner sc = new
Scanner(System.in);
System.out.println("1. Turn left");
System.out.println("2. Turn right");
int ch =
sc.next().charAt(0);
if(ch == '1')
{
if (a==1 && turnLeft(a) && s ==
12)
return true;
else if (a==3 && turnLeft(a) &&
s == 29)
return true;
}
if(ch == '2')
{
if(a==2 && turnRight(a) && s ==
17)
return true;
}
return
false;
}
public static void main(String[]
args) {
Scanner sc = new
Scanner(System.in);
int
opt=1,num1,num2,num3;
System.out.println("Enter first number: ");
num1 =
sc.nextInt();
System.out.println("Enter second number: ");
num2 =
sc.nextInt();
System.out.println("Enter third number: ");
num3 =
sc.nextInt();
ComboLock lock =
new ComboLock(num1,num2,num3);
if
(menu_list(opt,num1))
opt++;
if(opt == 2)
{
if (menu_list(opt,num2)) {
opt++;
}
}
if(opt == 3)
{
if (menu_list(opt,num3)) {
open();
}
}
else
System.out.println("Invalid Input");
}
}
Output Screenshot: