我的理解是,将存在一个静态变量,以便在变量所在的类的所有实例之间共享。
我的代码如下:
public class Game {
private static final ArrayList<Game> GAMESLIST = new ArrayList<Game>();
Random rand = new Random();
private int gameID;
private int teamScore1;
private int teamScore2;
private int temperature;
private String teamName1;
private String teamName2;
public void PlayGame(Team team1, Team team2, int value, String teamNameValue1, String teamNameValue2, Scheduler scheduler){
temperature = value;
int maxGoals = 2;
int iterator;
if(temperature > 12){
for(iterator = 0; iterator < temperature; ++iterator){
++maxGoals;
if(maxGoals == 8){
break;
}
}
}
teamScore1 = rand.nextInt(maxGoals);
teamScore2 = rand.nextInt(maxGoals);
teamName1 = teamNameValue1;
teamName2 = teamNameValue2;
++gameID;
System.out.println(teamScore1);
System.out.println(teamScore2);
GAMESLIST.add(this);
scheduler.PlayGame();
}
public void PrintStatistics(){
int iterator;
for(iterator = 0; iterator < this.GAMESLIST.size(); ++iterator){
System.out.println("Game# " +this.GAMESLIST.get(iterator).gameID);
System.out.println("Team 1: " +this.GAMESLIST.get(iterator).teamName1);
System.out.println("Team 2: " +this.GAMESLIST.get(iterator).teamName2);
System.out.println(GAMESLIST.get(iterator).teamScore1);
System.out.println(GAMESLIST.get(iterator).teamScore2);
System.out.println("Recorded temperature that day: " + GAMESLIST.get(iterator).temperature);
}
}
public class Scheduler {
Random rand = new Random();
private Team[] teams;
private Team team1, team2;
private Game game;
private int temperature;
private int numberOfColdDays = 0;
public Scheduler(){
}
public Scheduler(Game gameValue, Team[] teamsValue){
game = gameValue;
teams = teamsValue;
}
public void PlayGame(){
if(IsTooCold() == true){
System.out.println("Too cold to play!");
++numberOfColdDays;
if(numberOfColdDays < 3){
SoccerLeague.PlayGame(this);
}
else{
SoccerLeague.EndSeason(this);
}
}
else{
numberOfColdDays = 0;
TeamPicker(teams);
game.PlayGame(team1, team2, temperature, team1.teamName, team2.teamName, this);
}
}
public void TeamPicker(Team[] teams){
int value1;
int value2;
value1 = rand.nextInt(3);
team1 = teams[value1];
do{
value2 = rand.nextInt(3);
team2 = teams[value2];
}while(value1 == value2);
}
public boolean IsTooCold(){
boolean tOrF = false;
System.out.println("Is it too cold to play?");
this.temperature = rand.nextInt(30);
if(temperature < 7){
tOrF = true;
}
return tOrF;
}
public void PrintGames(){
}
}
在IDE中运行调试器时,我会在this
内为ArrayList
类型的一个实例创建无限量的Game
对象实例。
此外,在满足特定条件并且打印ArrayList
之后,for
循环将随机打印一次,并打印随机数量的实例那个先前创建的迭代。
我的代码在Game
类,PlayGame
方法或PrintStatistics
方法中失败了吗?
另请注意,我已尝试完全从this
方法中的循环中删除PrintStatistics
关键字,但我仍然得到相同的结果。
与往常一样,任何帮助都表示赞赏。
编辑 根据要求,调度程序类。
问候,MYLESMAN
答案 0 :(得分:0)
你有无明显的无限循环。
你有一个方法Game.PlayGame,它将你的游戏添加到列表并调用scheduler.PlayGame()。但是,scheduler.PlayGame()在其轮流中调用game.PlayGame()。它导致多次向游戏列表添加游戏,并可能导致StackOverflowError和OutOfMemoryError。