I'm a beginner in Java and I am making a basic game for practice. I'm almost done, but I have one further obstacle to overcome.
I would like to know how to make the game loop on the game()
method after pressing no as a choice when asked whether to end the game.
Here is my code:
private static void game() //game method
{
//...
int play = JOptionPane.showOptionDialog(null
,"End"
, "Do you want to play again?"
, JOptionPane.PLAIN_MESSAGE
,JOptionPane.DEFAULT_OPTION
, null
, again
, again[1]);
//end of game
if (play == 0)
System.exit(0);//exit
else
/* what do I put here to restart the program in the same method(game())
after pressing the No button on the JOptionPane??? */
System.out.println("Service not available");
To anybody who can help, I thank you very much!
If you just want to make it work you can do something like this :
// Game method
private static void game() {
boolean exit = false;
while (!exit) {
// int play = JOptionPane.showOptionDialog(null, "Play Again?", "Do you want to play again?", JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, again, again[1]);
// End of game
if (play == 0) {
exit = true;
}
}
// Exit
System.exit(0);
}
But a better more professional approach would be to refactor your code, so you extract game logic and separate it from User dialog interaction.