我有用Java編寫的Sudoku遊戲。遊戲的主要過程是主要方法。我有一個while循環,其中我有myClassObject.getCommandFromScanner()函數來讀取輸入與掃描儀,所以用戶可以填補數獨板上的空位或從菜單中選擇其他選項(例如保存,顯示解決方案和退出到主菜單)。此循環僅在用戶選擇退出到菜單時結束,因爲函數myClassObject.getCommandFromScanner()僅在該情況下返回false。 ((((System.currentTimeMillis() - nGame.timeAtStart < 10000)& & myClassObject.getCommandFromScanner()))< - 第一次第一次,第一次,第一次,第一次,我想設置遊戲的指定時間,但不能在while循環條件爲真,並且循環可以等待用戶輸入。只有當用戶輸入了某些內容時,循環條件纔會再次chceck,然後退出該循環。我怎麼解決這個問題?我也嘗試使用ExecutorService,它幾乎工作,循環執行指定的時間,但它然後退出菜單,用戶無法啓動新遊戲。掃描儀停止正常工作,我的主窗口與遊戲崩潰...我在這裏是新的,所以很抱歉,如果我的問題不夠清楚。我希望你能幫助我如何設置方法的最大執行時間?
public class Sudoku
{
public static void main(String[] args) throws Exception
{
while(course != exit)
{
opt = new String(in.next());
int option;
option = Character.getNumericValue(opt.codePointAt(0));
if(course == menu)
{
//go to menu
}
else if(course == newGame)
{
//setup new game
}
if(course == game)
{
nGame.timeAtStart=System.currentTimeMillis();
myClassObject.setGame(newGame);
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(new Runnable() {
@Override
public void run() {
try{
while(myClassObject.getCommandFromScanner());
}
catch(Exception e) {}
}
});
executor.shutdown();
try {
future.get(8, TimeUnit.SECONDS); //
} catch (InterruptedException e) { //
System.out.println("job was interrupted");
} catch (ExecutionException e) {
System.out.println("caught exception: " + e.getCause());
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("Your game timed out!");
}
course.printMessage("TIMEOUT");
course = menu;
}
}
}
}
這是我的代碼的原始版本:
public class Sudoku
{
public static void main(String[] args) throws Exception
{
while(course != exit)
{
opt = new String(in.next());
int option;
option = Character.getNumericValue(opt.codePointAt(0));
if(course == menu)
{
//go to menu
}
else if(course == newGame)
{
//setup new game
}
if(course == game)
{
nGame.timeAtStart=System.currentTimeMillis();
myClassObject.setGame(newGame);
while(myClassObject.getCommandFromScanner()); //while user don't choose 'menu' option, read input from keyboard
course = menu; //user choose 'menu', go to menu section
}
}
}
} 我要爲遊戲的最大時間,然後顯示消息:「超時」和去主菜單
[在Java超時方法(http://stackoverflow.com/questions/8982420/time-out-method-in-java)所有的 – brummfondel