简体   繁体   English

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

[英]How can I check if the char array has an empty cell so I can print 0 in it?

Code: 码:

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';
            }
        }
}

Change it to: if(position[i][j] == 0) 将其更改为: if(position[i][j] == 0)
Each char can be compared with an int. 每个char都可以与int进行比较。
The default value is '\' ie 0 for a char array element. 默认值为'\'即char数组元素为0
And that's exactly what you meant by empty cell , I assume. 而这正是你所说的empty cell意思。

To test this you can run this. 要测试这个,你可以运行它。

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.");
                }
            }
        }
    }

}

Assuming you have initialized your array like 假设你已经初始化了你的数组

char[] position = new char[length];

the default value for each char element is '\' (the null character ) which is also equal to 0 . 每个char元素的默认值'\'空字符 ),它也等于0 So you can check this instead: 所以你可以检查一下:

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

or use this if you want to improve readability: 如果您想提高可读性,请使用此选项:

if (positionv[i][j] == 0)
 if(position[i][j]==0)
{
 // The index value of [i][j] is 0
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM