So here are my code segements:
1. The Interface with problem Im trying to solve
// Design a Java interface Lockable that includes the following methods: setKey, // lock, unlock, and locked. The setKey, lock, and unlock methods take an // integer parameter that represents the key. The setKey method establishes // the key. The lock and unlock methods lock and unlock the object, // but only if the key passed in is correct. The locked method returns a // boolean indicating whether or not the object is locked. A Lockable object // represents an object whose regular methods are protected: if the object is // locked, the method cannot be invoked; if it is unlocked, they can be invoked. // Redesign and implement a version of this Coin class so that it is Lockable. public interface Lockable { boolean locked(); void setKey(int password); boolean lock(int password); boolean unlock(int password); }
2. The class coin with modifications:
public class Coin implements Lockable { private int key; // password to make it lockable private boolean locked; // if true, object is locked private final int HEADS = 0; private final int TAILS = 1; private int face; public boolean locked() { return this.locked; } public void setKey(int password) { this.key = password; this.locked = true; } public boolean lock(int password) { if (password == this.key) { this.locked = true; return true; } else { return false; } } public boolean unlock(int password) { if (password == this.key) { this.locked = false; return true; } else { return false; } } public Coin() { locked = true; } public boolean flip() { if (this.locked == false) { face = (int) (Math.random() * 2); return true; } return false; } public boolean isHeads() { return (face == HEADS); } public String toString() { if (this.locked == false) { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; } else return ""; } }
3. Since the questions asked for only the methods, i believe thats as far he wants us to go but he made a driver to test if it worked, something similar to this
public class Driver { public static void main(String[] args) { Coin myCoin = new Coin(); boolean bSuccess, bResult; myCoin.setKey(1234); bSuccess = myCoin.flip(); // Should Fail, coin is locked bResult = myCoin.unlock(12345); if (bResult) // coin is unlocked { myCoin.flip(); boolean iValue = myCoin.isHeads(); } else { System.out.println("You better remember the LOCK value"); } } }
Some errors I get when running this:
1. After prompting for the password it does nothing
2. Even i tried to tidy the code, some variables were left behind since the program for this situation.
If someone could help me fix my Driver class and allowing Coin to implement it
Thanks everyone in Advance!