此代码的目标是为我的主类Coin
设置一个可锁定的界面,使用户输入key
来访问主代码。但是,我不知道如何以可锁定对象保护常规方法(setKey
,lock
和unlock
)以及此对象被锁定的方式编写驱动程序类,如果解锁则无法调用方法,可以调用它们。我试过一个司机,但它没有用。
package coins;
import java.util.Scanner;
public class Coins {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int guess;
System.out.println("Enter key: ");
guess = scan.nextInt();
Coin key = new Coin();
System.out.println(key);
final int flips = 1000;
int heads = 0, tails=0;
Coin myCoin = new Coin ();
for (int count =1; count <= flips; count++) {
myCoin.flip();
if (myCoin.isHeads())
heads++;
else
tails++;
}
System.out.println ("The number flips: " + flips);
System.out.println ("The number of heads: " + heads);
System.out.println ("The number of tails: " + tails);
}
}
硬币等级
package coins;
class Coin implements Lockable {
private final int HEADS = 0;
private final int TAILS = 1;
private boolean locked;
private int key;
private int face;
public Coin () {
flip();
locked = false;
key = 123;
}
public void flip() {
face = (int) (Math.random()*2);
}
public boolean isHeads() {
return (face == HEADS);
}
public String toString() {
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
public boolean locked(){
return locked;
}
public void setKey(int key){
this.key = key;
}
public void unlock(int key){
if(this.key == key){
locked = false ;
}
}
public void lock(int key){
if(this.key == key){
locked = true;
}
}
public void messageReturn(){
if(locked == false)
System.out.println("unlocked") ;
}
}
可锁定界面
public interface Lockable {
public void setKey (int key);
public void lock (int key);
public void unlock (int key);
public boolean locked();
}
答案 0 :(得分:0)
首先,您应该通过以下方式检查猜测是否正确:( main
)
key.unlock(guess);//and you might want to set the default of locked to true, and remove the flip() in the constructor
您需要在每种方法中添加一个检查:
public void flip()
{
if(!locked)
face = (int) (Math.random()*2);
}
与其他方法类似。
答案 1 :(得分:0)
Itamar Green说的是真的。但是,对我而言,您所描述的真正问题似乎是Coins
课程,而不是Coin
课程。您实际上并没有使用用户输入的guess
键执行任何操作。您需要使用该密钥在setKey()
上致电Coin
。然后,您的Coin
将根据您的代码和Itamar的答案调用或不调用方法,首先检查它是否处于锁定状态。