How to check if a character is correct

前端 未结 4 1875
情话喂你
情话喂你 2021-01-23 05:04

I have a bunch of characters and want to remove everything that isn\'t a \'#\' \'.\' \'E\' and \'G\'.

I tried to use this:

if (buffer.get(buffertest) ==          


        
相关标签:
4条回答
  • 2021-01-23 05:32

    You haven't shown the type of buffer, which makes things harder. But assuming buffer.get returns a char, you could use:

    if ("GE#.".indexOf(buffer.get(buffertest) >= 0)
    

    Or you could check each option explicitly, as per Simulant's answer... or to do the same thing but only calling get once:

    char x = buffer.get(buffertest);
    if (x == 'G' || x == 'E' || x == '#' || x == '.')
    

    Your original code is failing because | is trying to perform a bitwise "OR" operation on the four characters... it's not the same thing as performing a logical "OR" on four conditions.

    0 讨论(0)
  • 2021-01-23 05:36
    if (buffer.get(buffertest) == 'G'||
     buffer.get(buffertest) == 'E'||
     buffer.get(buffertest) == '#'||
     buffer.get(buffertest) == '.')
    
    0 讨论(0)
  • 2021-01-23 05:39

    You need to compare for each character individually. Assuming that buffer.get(buffertest) returns a char, here's how to do it:

    char c = buffer.get(buffertest);
    if (c == 'G' || c == 'E' || c == '#' || c == '.') {
        // do something
    }
    

    Alternatively, you could do something like this:

    char c = buffer.get(buffertest);
    if ("GE#.".contains(Character.toString(c))) {
        // do something
    }
    
    0 讨论(0)
  • 2021-01-23 05:48

    This root problem is incorrect use of the bitwise OR operator, and the Java operator precedence hierarchy. Java expressions of this type are evaluated left to right, and the == operator takes precedence over |. Which when combined, your expression roughly translates to:

    (buffer.get(buffertest) == 'G') | 'E' | '#' | '.'
    

    The first part of the expression buffer.get(buffertest) == 'G' evaluates to a boolean.<br> The second part of the expression'E' | '#' | '.'` evaluates to an int, which is narrowed to a char

    Which leads to an incompatible type compile time error. You can correct your code by expanding the check this way:

    char ch = buffer.get(buffertest);
    if(ch == 'G' || ch == 'E' || ch == '#' || ch == '.') {
       // do something
    }
    
    0 讨论(0)
提交回复
热议问题