How to check if a character is correct

前端 未结 4 1917
情话喂你
情话喂你 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: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.
    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
    }
    

提交回复
热议问题