0

I am trying to make a program that will convert a String to Binary. To do that I converted the User Input to char array. Using for loops to read the characters in the char array one by one.

My Problem is how can I read spaces from the char Array. Here's my code.

    for(int i = 0 ; i < UserInput.length() ; i++) {
    char c = UserInput.charAt(i);

        if (Character.isLetter(c)){
            System.out.print ("letter");
        }
        else if (Character.isDigit(c)){
            System.out.print ("number");
        }
        else if (c== " "){
            System.out.print ("space");
        }
        else
        {
            System.out.println ("Special Char");
        }
    }

The Errors shows bad operand types for binary operator '=='else if ((c) == " ")

Hülya
  • 3,353
  • 2
  • 12
  • 19

4 Answers4

3

c is of type character and you're trying to compare it to " " which is of type string, if you want to check if c is a space you should compare it to ' ' which is also of type character.

Mark
  • 5,089
  • 2
  • 20
  • 31
1

You can't compare a string with array.

One space character is represented by ' ' and not " "

Just change this,

if (c== " ")

to

if (c== ' ')
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
1

You are trying to compare Character with a String. That's why the error. Try using

Character.isSpaceChar(c)

Hope this works for you.

Pranali Rasal
  • 177
  • 2
  • 12
  • `isSpaceChar` considers more types of whitespace than just the basic space (ASCII 0x20, Unicode U+0020), given the given code that might not be what the OP wants. – Mark Rotteveel Oct 23 '18 at 14:54
0

While

if(c==' ')

would work for the standard whitespace character there are actually multiple different types of whitespaces like non-breaking-spaces for example.

But just like for letters and digits there already exists a function in Character to check if a character is any of those whitespaces:

if(Character.isWhitespace(c))
OH GOD SPIDERS
  • 3,091
  • 2
  • 13
  • 16