【问题标题】: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。

标签: java loops char compare charat


【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 2013-07-20
        • 1970-01-01
        • 1970-01-01
        • 2023-01-14
        • 1970-01-01
        • 2012-05-01
        • 2013-12-22
        • 1970-01-01
        • 2020-03-11
        相关资源
        最近更新 更多