如何检查 char 数组是不是有一个空单元格,以便在其中打印 0?

Posted

技术标签:

【中文标题】如何检查 char 数组是不是有一个空单元格,以便在其中打印 0?【英文标题】:How can I check if the char array has an empty cell so I can print 0 in it?如何检查 char 数组是否有一个空单元格,以便在其中打印 0? 【发布时间】:2014-02-25 11:49:49 【问题描述】:

代码:

public void placeO(int xpos, int ypos) 
    for(int i=0; i<3;i++)
        for(int j = 0;j<3;j++) 
            // The line below does not work. what can I use to replace this?
            if(position[i][j]==' ') 
                position[i][j]='0';
            
        

【问题讨论】:

Character.UNASSIGNED比较——不是''或0。 【参考方案1】:
 if(position[i][j]==0)

 // The index value of [i][j] is 0

【讨论】:

【参考方案2】:

将其更改为:if(position[i][j] == 0) 每个 char 都可以与一个 int 进行比较。 默认值为'\u0000',即0 用于char 数组元素。 我猜这正是你所说的empty cell 的意思。

要对此进行测试,您可以运行它。

class Test 

    public static void main(String[] args) 
        char[][] x = new char[3][3];
        for (int i=0; i<3; i++)
            for (int j=0; j<3; j++)
                if (x[i][j] == 0)
                    System.out.println("This char is zero.");
                
            
        
    


【讨论】:

【参考方案3】:

假设你已经初始化了你的数组

char[] position = new char[length];

the default value for each char 元素是'\u0000'空字符),它也等于0。所以你可以检查这个:

if (postision[i][j] == '\u0000')

如果您想提高可读性,请使用它:

if (positionv[i][j] == 0)

【讨论】:

以上是关于如何检查 char 数组是不是有一个空单元格,以便在其中打印 0?的主要内容,如果未能解决你的问题,请参考以下文章