简体   繁体   English

如何检查角色是否正确

[英]How to check if a character is correct

I have a bunch of characters and want to remove everything that isn't a '#' '.' 我有很多角色,想要删除所有不是'#''的东西。 'E' and 'G'. 'E'和'G'。

I tried to use this: 我试着用这个:

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

But got an issue with an incompatible type. 但是出现了不兼容类型的问题。

This root problem is incorrect use of the bitwise OR operator, and the Java operator precedence hierarchy. 这个根问题是使用按位OR运算符和Java运算符优先级层次结构。 Java expressions of this type are evaluated left to right, and the == operator takes precedence over |. 此类型的Java表达式从左到右计算,而==运算符优先于|。 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' | 表达式buffer.get(buffertest) == 'G' evaluates to a boolean.<br> The second part of the expression的第一部分buffer.get(buffertest) == 'G' evaluates to a boolean.<br> The second part of the expression 'E' buffer.get(buffertest) == 'G' evaluates to a boolean.<br> The second part of the expression '#' | '#'| '.'` evaluates to an int, which is narrowed to a char '。'`计算为int,缩小为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
}

You haven't shown the type of buffer , which makes things harder. 你没有显示buffer的类型,这使事情变得更难。 But assuming buffer.get returns a char , you could use: 但假设buffer.get返回一个char ,您可以使用:

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: 或者你可以明确地检查每个选项,根据Simulant的答案......或者做同样的事情,但只调用get一次:

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 . 试图对四个字符执行按位“或”运算......这与在四个条件下执行逻辑“或”不同。

You need to compare for each character individually. 您需要单独比较每个字符。 Assuming that buffer.get(buffertest) returns a char , here's how to do it: 假设buffer.get(buffertest)返回一个char ,这里是如何做到的:

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
}
if (buffer.get(buffertest) == 'G'||
 buffer.get(buffertest) == 'E'||
 buffer.get(buffertest) == '#'||
 buffer.get(buffertest) == '.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM