GregB GregB - 4 months ago 11
Java Question

Why can't I compare to '_' char in an "if" statement?

Trying to search a

StringBuffer
for appearances of the
_
character. My code is below but when I run I get
Match
printing for every digit in the
StringBuffer
.

Don't know if it makes a difference but am running this code on a learning website and so don't have a pure Java debugger. I have checked the standard escape characters and this isn't one of them so am out of ideas.

StringBuffer buffer = new StringBuffer(functionName);
System.out.println(buffer);
char compare='_';
char x;
for(int i=0;i<buffer.length();i++){
x = buffer.charAt(i);
System.out.println(x);
if(x==compare);
System.out.println("Match");
}


Thoughts anyone?

Answer

You can if you remove ; after the condition

if (x == compare) {
    System.out.println("Match");
}

For your case, it looks like

if (x == compare); // if `x` and `compare` are equal, we do nothing
System.out.println("Match"); // it prints out `Match` regardless of the condition