Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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';
            }
        }
}
like image 604
steven1816 Avatar asked Feb 01 '14 19:02

steven1816


People also ask

How do I check if a char array is empty?

The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0. char text[50]; text[0] = 0; From then, both strlen(text) and the very-fast-but-not-as-straightforward (text[0] == 0) tests will both detect the empty string.

What does an empty char array contain?

String arrays can contain both empty strings and missing values. Empty strings contain zero characters and display as double quotes with nothing between them ( "" ). You can determine if a string is an empty string using the == operator.

How do you check if a char is null?

A char cannot be null as it is a primitive so you cannot check if it equals null , you will have to find a workaround. Also did you want to check if letterChar == ' ' a space or an empty string? Since you have a space there.

How do you check if a char is in a char array?

The contains() method of Chars Class in Guava library is used to check if a specified value is present in the specified array of char values. The char value to be searched and the char array in which it is to be searched, are both taken as a parameter.


2 Answers

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

}
like image 89
peter.petrov Avatar answered Sep 22 '22 00:09

peter.petrov


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)
like image 26
Christian Tapia Avatar answered Sep 20 '22 00:09

Christian Tapia