简体   繁体   中英

How to check if a char is null

I want to check if the char is null or not? but why this code is not working? letterChar == null also is not working. I googled for many problems but didn't see any solutions, mostly the solutions are about String .

String letter = enterletter.getText().toString();
char letterChar = letter.charAt(0);


if(letterChar == ' ' || letterChar == NULL) // this is where the code won't works
{
    Toast.makeText(getApplicationContext(), "Please enter a letter!", Toast.LENGTH_LONG).show();
}

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.

The first two answers here may be helpful for how you can either check if String letter is null first.

or cast char letterChar into an int and check if it equals 0 since the default value of a char is \ - (the nul character on the ascii table, not the null reference which is what you are checking for when you say letterChar == null )- which when cast will be 0 .

char is a primitive datatype so can not be used to check null.

For your case you can check like this.

        if (letterChar  == 0) //will be checked implicitly
        {
            System.out.println("null");
        }
        //or use this
        if (letterChar  == '\0')
        {
            System.out.println("null");
        }

From your code it seems like you work with Unicode and the method you search for is into Character class (java.lang)

Character.isLetter(ch);

It also contains lots of useful static method that can suite you. If so, the code will be

String letter = enterletter.getText().toString();
char letterChar = letter.charAt(0);

if(!Character.isLetter(letterChar))
{
    Toast.makeText(getApplicationContext(), "Please enter a letter!", Toast.LENGTH_LONG).show();
}

But if I would need to answer your question (without taking a look to your aim), then the code you need depends on what do you mean by "is char null".

In Java char cannot be == null. If you want to check if it is not an empty space, you need to do

 if (ch == ' ')

If you want to check if there are no line breakers (space, HT, VT, CR, NL and other), you should add the following to the proposed above:

if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\x0b')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM