我目前正在为我的大学考试项目工作。任务是创建棋盘游戏卢多。在编写了一些代码并进行了一些测试后,我遇到了 StackOverflowError。
所以这里是结构(5个类是必不可少的): Main.class GUI.class Game.class Player.class Piece.class
Main 创建了一个名为 mainGUI 的 GUI 类型的新对象。这为游戏创建了视觉效果,包括一个带有开始按钮的小设置区域。
在按下开始按钮时,会创建一个 Game 类型的新对象,然后创建 4 个 Player 类型的新对象(显然是 4 个玩家)。
在创建 Player 类型的对象时,此类型获取参数“nmbr”,该参数仅说明播放器的编号(Player1、Player2 等)。
每个玩家有 4 个棋子在棋盘上四处移动,因此这 4 个玩家中的每一个都创建了另外 4 个类型为 Piece 的对象。
现在当按下开始按钮时,应该发生的是,棋子显示在棋盘上。但这不会发生。相反,我收到一条错误消息,指出在调用第一个 Player 对象时存在 StackOverflowError。
因此,我尝试阅读 java 和 StackOverflow 中对象创建的行为以及类似的东西。但我在这里能得到的唯一结论是,我在彼此内部创建了太多对象。
public class Main {
public static void main(String[] args){
Main start = new Main();
start.activate();
}
static GUI mainGui;
public Main() {
mainGui = new GUI();
}
在 GUI 中有 JButton 'submit' 这个按钮应该通过创建 Game 类型的对象来启动游戏。
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object btn = e.getSource();
boolean ACTIVE = ((JButton) btn).isEnabled();
if (ACTIVE) {
submit.setVisible(false);
cancel.setVisible(true);
Game spiel = new Game();
spiel.begin();
}
}
});
public class Game {
public Game() {
}
Player player1 = new Player(1); //this is where the Error occurs
Player player2 = new Player(2);
Player player3 = new Player(3);
Player player4 = new Player(4);
}
etc.
public class Player extends Game {
private String name;
private Color color;
private boolean artiPlayer;
private int playerNmbr, start, end;
private int[] startArea, endArea;
Piece piece1, piece2, piece3, piece4;
public Player(int nmbr){
if (nmbr == 1) {
System.out.println("1.1");
piece1 = new Piece(500,175, Color.BLUE, Main.mainGui);
piece2 = new Piece(550, 175, Color.BLUE, Main.mainGui);
piece3 = new Piece(500,125, Color.BLUE, Main.mainGui);
piece4 = new Piece(550, 125, Color.BLUE, Main.mainGui);
start = 0;
end = 64;
}
}
Type Piece => Piece(xPos, yPos, Color, GUI)
//and so on
这是确切的错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at spielPackage.Player.<init>(Player.java:18)
at spielPackage.Game.<init>(Game.java:9)
对不起,如果代码有点不干净。我对java相当陌生,这仍然是一项正在进行的工作。
在这一点上,我不知道为什么 Java 会抛出一个StackOverflowError