Java 如何从方法重新启动程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34837441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to restart a program from a method
提问by Robolt Activator
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.
我是 Java 的初学者,我正在制作一个基本的练习游戏。我快完成了,但我还有一个障碍需要克服。
I would like to know how to make the game loop on the game()
method after pressing noas a choice when asked whether to end the game.
当被问及是否结束游戏时,我想知道如何game()
在按no作为选择后使游戏在该方法上循环。
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!
对于任何可以提供帮助的人,我非常感谢您!
采纳答案by Hamdi Douss
If you just want to make it work you can do something like this :
如果你只是想让它工作,你可以做这样的事情:
private static void game()//game method
{
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;
}
}
System.exit(0);//exit
But a better more professionnal approach would be to refactor your code, so you extract game logic and separate it from User dialog interaction.
但是更好更专业的方法是重构您的代码,以便您提取游戏逻辑并将其与用户对话框交互分开。
回答by Arc676
Given the current state of your program, the easiestsimplestmost straightforwardreadable method is recursion. Just call your game method again. Note that there's probably a recursion limit, so the loop is the recommended method, even if it does involve restructuring your code a bit.
给定程序的当前状态,最简单最直接易读的方法是递归。只需再次调用您的游戏方法。请注意,可能存在递归限制,因此循环是推荐的方法,即使它确实涉及稍微重构您的代码。
else{
game();
}
Loop method: declare play
at the beginning and use a loop:
循环方法:play
在开头声明并使用循环:
private static void game(){
boolean play = true;
while (play){
//...
//find out if user wants to play again
//set play to false if player doesn't want to play anymore
}
}
回答by karim mohsen
Extract the JOptionPane
part from your game()
function code
JOptionPane
从您的game()
功能代码中提取零件
int play=0;
do{
game();
play = JOptionPane.showOptionDialog(null
,"End"
, "Do you want to play again?"
, JOptionPane.PLAIN_MESSAGE
,JOptionPane.DEFAULT_OPTION
, null
, again
, again[1]);
}while(play);