我正在尝试制作一款垄断类型的游戏,但我的棋盘遇到了一些问题。我制作了一个单独的程序,只测试主板,所以我有一个 Main、一个 Board 和一个 Square 类。 当我尝试注册一个正方形时,我的 Board 类将特定的正方形注册到我的 Square 类时遇到问题。我正在提供我的测试程序的代码,并且所有导入都是正确的,因此我需要一些帮助来解决我在这里的错误:
public class Main {
public static void main(String[] args) {
Board board = new Board();
board.addSquare("0,Country in conflict.", "Nothing");
board.getSquare(0);
}
}
这是我的董事会类(class):
public class Board {
public ArrayList<Square> Squares;
public void addSquare(String square,String action){
Square sq = new Square(square, action);
Squares.add(sq);
}
public void getSquare(int square){
System.out.println(Squares.get(square));
}
}
这是我的 Square 类:
public class Square{
public ArrayList<String> actions;
public final String text;
public final int squareNumber;
public Square(String textGiven, String action){
String textArray[] = textGiven.split(",");
this.squareNumber = Integer.parseInt(textArray[0]);
this.text = textArray[1];
actions.add(action);
}
public String getAction(String action){
return action;
}
public int getNumber(){
return squareNumber;
}
public String getText(){
return text;
}
public String toSrting(){
return squareNumber + ". " + text;
}
}
最佳答案
您的 Square 类正在抛出 NullPointerException
在您的ArrayList<String> actions
上因为你还没有初始化它。您可以添加这一行:
this.actions = new ArrayList<>();
在通过.add(...);
访问你的构造函数之前
我还建议您更改您的 Board::addSquare(String, String)
方法Board::addSquare(Square)
因为这将 Square-logic 排除在董事会之外。如果您始终了解 Square 及其操作,您也可以更改 Square 类的构造函数。当我开始编码时,我也这样做了很多次,但结果证明它不那么复杂,并且对于其他人来说是更易读的代码。
编辑:感谢@Nexevis
您的 Board 类与您的 Squares
有同样的问题数组列表
关于java - 为什么我不能将非常规类型 Arraylist<> 注册到 ArrayList<> 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59788600/