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

假装没事ソ 提交于 2019-12-21 17:07:31

问题


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

回答1:


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

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

}



回答2:


Assuming you have initialized your array like

char[] position = new char[length];

the default value for each char element is '\u0000' (the null character) which is also equal to 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)



回答3:


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


来源:https://stackoverflow.com/questions/21502859/how-can-i-check-if-the-char-array-has-an-empty-cell-so-i-can-print-0-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!