java - Char 数组索引不接受

标签 java multidimensional-array null char incompatibility

我在玩井字棋模拟游戏时遇到问题。我使用二维数组来表示游戏板,并按如下方式实例化它。我需要使用 char 类型数组。我意识到我不必指定每个索引为 null,因为这是 char 的默认值,但我想我应该尝试一下。

public TicTacToe2D()
{
    board = new char[3][3];

    for(int i = 0; i < board.length; i++)
    {
        for(int j = 0; j < board[i].length; j++)
        {
            board[j] = null;
        }

        board[i] = null;
    }         
}

这里我正在检查获胜条件,看看索引是否彼此相等并且不为空(默认值),尽管我尝试使用“”作为数组初始值。在这种情况下,我收到错误:“不兼容的类型:char 无法转换为 char[]”

public char isWin()
{
    //Check for row wins
    if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] != null)
        return true;

    if (board[1][0]==board[1][1] && board[1][1]==board[1][2] && board[1][0] != null)
        return true;

    if (board[2][0]==board[2][1] && board[2][1]==board[2][2] && board[2][0] != null)
        return true;

    //Check for column wins
    if (board[0][0]==board[1][0] && board[1][0]==board[2][0] && board[0][0] != null)
        return true; 

    if (board[0][1]==board[1][1] && board[1][1]==board[2][1] && board[0][1] != null)
        return true; 

    if (board[0][2]==board[1][2] && board[1][2]==board[2][2] && board[0][2] != null)
        return true; 

    //Check for diagonal wins
    if (board[0][0]==board[1][1] && board[1][1]==board[2][2] && board[0][0] != null)
        return true; 

    if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != 0)
        return true; 
    else return false;
}

检查索引是否为空时,出现错误“不可比较的类型:char 和” 任何帮助将不胜感激!

最佳答案

数据类型char是原始数据类型,因此它不能为null。但默认值是空字符\0(或\u0000)。 JLS Section 4.12.5给出默认值:

  • For type char, the default value is the null character, that is, '\u0000'.

尝试将其与 \0\u0000 进行比较,而不是与 null 进行比较。

关于java - Char 数组索引不接受,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22082339/

相关文章:

java dom解析器-如何检查元素是否为空

sql - 数据库:选择最后的非空条目

string - 为什么看似空的文件和字符串会产生 md5sum?

python - 在 ndim(第四个轴)中堆叠数组并使用 numpy 应用旋转

c - C 中使用 qsort 对多维数组进行排序

php - 如何使用 CodeIgniter 的 ActiveRecord 选择列值不为 NULL 的行?

java - 二维数组中的最小数字无法正常工作

java - 带有外部第三方 jar 的 Eclipse 插件

java - 用Java读取纯文本文件

php - 如何按多列对多维数组进行排序?