Java 如何检查字符数组是否有一个空单元格,以便我可以在其中打印 0?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21502859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:02:28  来源:igfitidea点击:

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

javaloopscharcomparecharat

提问by steven1816

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

采纳答案by peter.petrov

Change it to: if(position[i][j] == 0)
Each char can be compared with an int.
The default value is '\u0000'i.e. 0for a char array element.
And that's exactly what you meant by empty cell, I assume.

将其更改为:if(position[i][j] == 0)
每个字符都可以与一个整数进行比较。
默认值是'\u0000'ie0用于 char 数组元素。
这正是你的意思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.");
                }
            }
        }
    }

}

回答by Kick

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

回答by Christian

Assuming you have initialized your array like

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

char[] position = new char[length];

the default value for each charelement is '\u0000'(the null character) which is also equal to 0. So you can check this instead:

每个char元素的默认值'\u0000'空字符),它也等于0。所以你可以检查这个:

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

or use this if you want to improve readability:

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

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