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

码:

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

将其更改为: if(position[i][j] == 0)
每个char都可以与int进行比较。
默认值为'\u0000'即char数组元素为0
我认为这正是你对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."); } } } } } 

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

 char[] position = new char[length]; 

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

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

如果您想提高可读性,请使用此选项:

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