I have a Sudoku game written in Java. The main course of the game is in main method. I have a while loop, in which I have myClassObject.getCommandFromScanner() function to read input with Scanner, so user can fill the empty position on a sudoku board or choose other option from menu(for example save, show solution and exit to main menu). This loop ends only if user choose exit to menu, because function myClassObject.getCommandFromScanner() return false only in that case. I want to set the specified time of game, but cannot do it in while loop (while((System.currentTimeMillis()-nGame.timeAtStart < 10000) && myClassObject.getCommandFromScanner())) <- for the first time the first condition is true and loop can wait for user input on and on. Only if user enter something, the loop condition is chceck again and then exit from this loop. How can I solve this problem? I also try to use ExecutorService and it almost work, the loop is executing for specified time, but then it exit to menu and user cannot start new game. Scanner stop working correctly and my main window with game is crashed... I am new here so sorry if my question isn't clear enough. I hope you will help me
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;
}
}
}
}
This is original version of my code:
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
}
}
}
} I want to set the max time for game, then show message: "timeout" and go to main menu