I am working on this program where at the end of the game I ask the user if they want to play again. If they say yes, I need to start a new game. I made a restart() method:
我正在制作这个节目,在比赛结束时我会询问用户是否想再次播放。如果他们说是,我需要开始一个新游戏。我做了一个restart()方法:
public void restart(){
Game g = new Game();
g.playGame();
}
However when I call this method some of the values in my program stay at what they were during the previous game.
但是当我调用这个方法时,我程序中的一些值保持在上一个游戏中的状态。
Is there a game to just clear everything and create an new instance of the game with all the default values?
是否有游戏只是清除所有内容并使用所有默认值创建游戏的新实例?
3 个解决方案
#1
Without more information, I'd guess that your problem is likely that you use static variables, the values of which will persist across all instances of a given class. If you make them all into member variables and initialize them in your constructor, it should work.
如果没有更多信息,我猜你的问题可能是你使用的静态变量,其值将在给定类的所有实例中持续存在。如果将它们全部转换为成员变量并在构造函数中初始化它,它应该可以工作。
#2
Verify if those values that don't reset are reset in the Game constructor. Chances are they are not.
验证是否在Game构造函数中重置了那些未重置的值。他们可能不是。
Also are those values static? Static values don't reset by the constructor.
这些值也是静态的吗?构造函数不会重置静态值。
#3
Do you have any static variables? If yes, it is likely the problem. The value of static variables is maintained for new instances of your class. You can try to remove the static modifier and make sure you initialize all variables in the class constructor.
你有任何静态变量吗?如果是,那可能就是问题所在。为类的新实例维护静态变量的值。您可以尝试删除static修饰符,并确保初始化类构造函数中的所有变量。
#1
Without more information, I'd guess that your problem is likely that you use static variables, the values of which will persist across all instances of a given class. If you make them all into member variables and initialize them in your constructor, it should work.
如果没有更多信息,我猜你的问题可能是你使用的静态变量,其值将在给定类的所有实例中持续存在。如果将它们全部转换为成员变量并在构造函数中初始化它,它应该可以工作。
#2
Verify if those values that don't reset are reset in the Game constructor. Chances are they are not.
验证是否在Game构造函数中重置了那些未重置的值。他们可能不是。
Also are those values static? Static values don't reset by the constructor.
这些值也是静态的吗?构造函数不会重置静态值。
#3
Do you have any static variables? If yes, it is likely the problem. The value of static variables is maintained for new instances of your class. You can try to remove the static modifier and make sure you initialize all variables in the class constructor.
你有任何静态变量吗?如果是,那可能就是问题所在。为类的新实例维护静态变量的值。您可以尝试删除static修饰符,并确保初始化类构造函数中的所有变量。