Monday, 9 September 2013

Java combination lock

Java combination lock

I'm new to java programing and wanted to get an opinion on my coding and
if there was any way to make it cleaner or better. Or if there is a better
way to go about solving this problem.
Implement a class called CombinationLock that simulates a lock. Your lock
has 40 positions, 0-39. A combination has 3 numbers from that range, which
open the lock if turned in sequence right, left, right.
// MIchael Thompson
public class Lock
{
private boolean nutural = true;
private boolean flag1, flag2, flag3;
private int one, two, three;
private boolean unlock = true;
private int position = 0;
public Lock (int one, int two, int three)
{
this.one = one;
this.two = two;
this.three = three;
}
public void turnRight (int ticks) // turns the dial right the given
number of ticks
{
if (nutural)
{
position = (40 - ticks);
flag1 = false;
nutural = false;
if (position == one)
{
flag1 = true;
// System.out.println(position);
}
}
else
{
if (position - ticks > 0 )
{
position = position - ticks;
// System.out.println(position);
flag3 = false;
if (position == three)
{
flag3 = true;
}
}
else
{
position = (40 - (ticks - position));
flag3 = false;
// System.out.println(position);
if (position == three )
{
flag3 = true;
}
}
}
}
public void turnLeft (int ticks) // turns the dial left the given number
of ticks
{
if (position + ticks < 40 )
{
position = (position + ticks);
// System.out.println(position);
flag2 = false;
if (position == two )
{
flag2 = true;
}
}
else
{
position = ( (position + ticks) - 40 );
// System.out.println(position);
flag2 = false;
if (position == two)
{
flag2 = true;
}
}
}
public void reset ()// which sets the dial to 0
{
nutural = true;
flag1 = false;
flag2 = false;
flag3 = false;
}
public void open ()
{
if (!(flag1 && flag2 && flag3))
{
unlock = false;
System.out.println("Wrong combination!!");
}
else
{
System.out.println("Lock is open!!");
}
}
public static void main(String[] args)
{
Lock lock = new Lock(35, 12, 37);
lock.turnRight(5);
lock.turnLeft(17);
lock.turnRight(15);
lock.open();
}
}

No comments:

Post a Comment