Search code examples
javacomparisoncharconditional-statements

Java char comparison does not seem to work


I know you can compare chars in Java with normal operators, for example anysinglechar == y. However, I have a problem with this particular code:

do{ 
    System.out.print("Would you like to do this again? Y/N\n");
    looper = inputter.getChar();
    System.out.print(looper);
    if(looper != 'Y' || looper != 'y' || looper != 'N' || looper != 'n')
        System.out.print("No valid input. Please try again.\n");
}while(looper != 'Y' || looper != 'y' || looper != 'N' || looper != 'n');

The problem should not be the other method, inputter.getChar(), but I'll dump it anyway:

private static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
public static char getChar() throws IOException{
    int buf= read.read();
    char chr = (char) buf;
    while(!Character.isLetter(chr)){
        buf= read.read();
        chr = (char) buf;
    }
    return chr;
}

The output I'm getting is as follows:

Would you like to do this again? Y/N
N
NNo valid input. Please try again.
Would you like to do this again? Y/N
n
nNo valid input. Please try again.
Would you like to do this again? Y/N

As you can see, the char I put in is an n. It is then printed out correctly(hence it is to be seen twice). However, the comparison doesn't seem to become true.

I'm sure I'm overlooking something obvious.


Solution

  • Your logic is incorrect. It is always true that looper isn't 'Y' or it isn't 'y' or it isn't ...

    You want the logical operator for "and": &&

    if(looper != 'Y' && looper != 'y' && looper != 'N' && looper != 'n')
    

    and a similar change in your while condition.