PP 7.8 Write a Java interface called 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 that indicates whether or not the object is locked. A Lockable object represents an object whose regular methods are protected: if the object is locked, the methods cannot be invoked; if it is unlocked, they can be invoked. Write a version of the Coin class from Chapter 5 so that it is Lockable.
import java.util.Scanner;
interface Lockable{
public void setKey(int key);
public boolean lock(int key);
public boolean unlock(int kdy);
public boolean locked();
}
class Coin implements Lockable{
private int key;
private boolean locked;
private final int head = 0;
private final int tail = 1;
private int face;
public void setKey(int key) { this.key = key; }
public boolean lock(int key) {
if(this.key == key) { this.locked = true; return true;}
else { return false; }
}
public boolean unlock(int key) {
if(this.key == key) { locked = false; return true; }
else { return false; }
}
public boolean locked() { return locked; }
public Coin() { flip(); }
public int flip() { face = (int) (Math.random()*2); return face; }
public boolean heads() { return face == head; }
public String toString() {
String faceName;
if(face == head) faceName = "HEAD";
else faceName = "TAIL";
return faceName;
}
}
public class PP7_8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Coin coin = new Coin();
coin.setKey(1234);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter key");
int num = scanner.nextInt();
boolean result = coin.unlock(num);
if (result) {
coin.flip();
System.out.println(coin);
} else { System.out.println("Not correct"); }
}
}
< console >
Enter key
123
Not correct
Enter key
1234
HEAD
Enter key
1234
TAIL
'[JAVA] 개발' 카테고리의 다른 글
Java Software Solution Ch7_PP3 (0) | 2024.05.01 |
---|---|
Java Software Solution Ch7_PP2 (0) | 2024.05.01 |
Java Software Solution Ch11_PP3 ; Exception Class (0) | 2024.04.28 |
Java Software Solution Ch11_ PP1 ; Exception Class (try-catch) (0) | 2024.04.27 |
Java Software Solution Ch10_PP3 ; Interface (0) | 2024.04.26 |