【问题标题】:Java 2-D array returning NULL返回 NULL 的 Java 二维数组
【发布时间】:2019-03-06 18:25:05
【问题描述】:

我正在努力创建一个“基本”用户界面 connect4 游戏。我无法弄清楚为什么当我调用打印“板”时,我得到空值,作为回报。我没有初始化数组吗?如果是这样,我该怎么做? ~谢谢

我的构造函数...

public class Connect4{ 
    private String game[][];
    public Conncet4(String game[][]){
         this.game = game;
    }

用我的一种方法...

public void dropChipX(int colm){    
    for(int i = 0; i<game.length;i++) {
        for(int j = 0; j<game[0].length;j++) {
            if( j%2 == 0 )
                game[game.length-1][col] = "|";
            else
                game[i][j] = " ";
        }
    }

    if(game[game.length-1][colm] == " ")
        game[game.length-1][colm] = "X";
    else
        game[(game.length-1)-count][col] = "X";
    count++;

}

我还有一个 toString 可以打印出数组

public String toString() {
    String result = "";
    for(int i = 0; i<game.length;i++) {
        for(int j = 0; j<game[0].length;j++)
            result = (game[i][j]);
        result += "\n";
    }
    return result;
}

我遇到的问题是,当我运行我的 main 时,它返回 null

public class Connect4TextConsole {

public static void main(String[] args) {

    String fun[][] = new String[6][15];
    Connect4 connect = new Connect4(fun);

    connect.dropChipX(3);
    System.out.print(connect);
    connect.dropChipY(2);
    System.out.print(connect);
}

}

【问题讨论】:

  • 你的代码有很多错误。从拼写错误开始,然后您将Strings 与== 而不是compare 进行比较,然后,您还没有声明一些变量(例如count...我给您的建议是调试你的代码。调试是每个程序员必须具备的基本技能。祝你好运。

标签: java arrays null return


【解决方案1】:

我建议你重新考虑这段代码:

public class Connect4{ 
    private String game[][];
    public Conncet4(String game[][]){
         this.game = game;
    }
}

您应该在构造函数中制作该二维数组的防御性副本。

任何为您提供对传递给构造函数的游戏二维数组的引用的代码都可以修改该可变引用。您的私人指定没有任何意义。

【讨论】:

  • 非常好的提示!但是OP的代码错误太多了,无论是逻辑上还是语法上……
  • 同意。除了他的问题,我还要解决一些问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2022-01-10
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多