我在Java中構建一個控制檯遊戲,它的工作原理是這樣的:它爲您打印一個操作(例如:3 x 4),並且您必須編寫結果(本例中爲12),它會在1分鐘內給你操作,然後完成。Java的訪問線程的類屬性
我從一開始,我不得不使用線程來捕捉用戶輸入的知道,所以這是線程的邏輯:
public class UserInput extends Thread {
private int answer;
@Override
public void run() {
Scanner in = new Scanner(System.in);
while(true){
answer = in.nextInt();
}
}
public int getAnswer(){
return answer;
}
}
很簡單,現在遊戲的邏輯:
public static void play() {
Game game = new EasyGame();
UserInput ui = new UserInput();
long beginTime = System.currentTimeMillis()/1000;
ui.start();
boolean accepted = true;
while(timeLeft(beginTime)){
//PrintChallenge() prints an operation and store its result in game
if(accepted) game.PrintChallenge();
accepted = false;
if(ui.getAnswer() == game.getResult()) accepted = true;
}
}
//returns if current time is 60 seconds after initial time
public static boolean timeLeft(long time){
return (System.currentTimeMillis()/1000) < (time + 60);
}
但它不工作,它根本就不匹配UI的getAnswer()
與遊戲的getResult()
。我在這個線程和遊戲邏輯上做錯了什麼?
what's game.getResult()在做什麼? – user7294900
當法PrintChallenge()運行時,它打印屏幕(「3×4」爲例)上挑戰並存儲該挑戰到一個變量的結果,那麼game.getResult()返回該變量的值 – DcCoO
嘗試打印'遊戲。的getResult()'。 –