如何检查一个值是 A 还是 B 而另一个值是 A 还是 B?
How can I check if one value is A or B and another value is A or B?
我正在尝试做一些事情:
if (firstChoice == A || B && secondChoice == A || B){
//passes check.
}
从逻辑上讲,如果第一个和第二个选择是 A 或 B,我希望它通过。这个语法有效吗?有更好的方法吗?
if (((firstChoice == A) || (firstChoice == B)) && ((secondChoice == A) || secondChoice == B)))
{
//passes check.
}
你做不到== A || B
;你可以这样做(但不应该,见下文):
if ((firstChoice == A || firstChoice == B) &&
(secondChoice == A || secondChoice == B)) {
您将获得的可读性差不多。把它划成一条线可以更容易地遵循逻辑;水平滚动几乎总是一件坏事,在 &&
运算符处打破它是最可读的方式。
但是,有一种方法可以使其更具可读性:创建一个辅助方法,它可以执行您想要的操作。
private boolean isAorB(YourObject choice) {
return choice == A || choice == B;
}
那么您的 if 语句将是:
if(isAorB(firstChoice) && isAorB(secondChoice)) {
对于未来的读者,包括您自己,这将更具可读性,这正是您真正想要的。
if ((firstChoice == A || firstChoice == B) && (secondChoice == A || secondChoice == B)) {
//do stuff
}
这里要注意的是,当您在脑海中阅读 "firstChoice is equal to A or B" 时,像 (firstChoice == A || B)
这样的东西是有意义的,但对 Java 就没有意义。 || 的左右两边运算符必须评估为布尔值。 'B' 不是布尔类型(我假设),但条件 firstChoice == B
是。
此外,您可以使用圆括号来标记运算顺序,就像处理普通算术一样。即使不需要它们,通常也有助于提高可读性。
正如我在评论中提到的和其他人提到的,没有 shorthand 可以说 "if X equals A or B or C or..." 或类似的东西。你必须说 if (x == a || x == b || x == c)
,等等(COBOL 确实允许这种表达,但不幸的是,这个有用的特性还没有在太多其他语言的设计中找到它的方式。)
你可以说:
if (isOneOf(firstChoice, A, B) || isOneOf(secondChoice, A, B)) {
...
}
如果您像这样定义 isOneOf
方法:
@SuppressWarnings("unchecked")
public static <T> boolean isOneOf(T obj, T... choices) {
for (T choice : choices) {
if (choice.equals(obj)) {
return true;
}
}
return false;
}
[请注意,这允许有两个以上的选择。]
我正在尝试做一些事情:
if (firstChoice == A || B && secondChoice == A || B){
//passes check.
}
从逻辑上讲,如果第一个和第二个选择是 A 或 B,我希望它通过。这个语法有效吗?有更好的方法吗?
if (((firstChoice == A) || (firstChoice == B)) && ((secondChoice == A) || secondChoice == B)))
{
//passes check.
}
你做不到== A || B
;你可以这样做(但不应该,见下文):
if ((firstChoice == A || firstChoice == B) &&
(secondChoice == A || secondChoice == B)) {
您将获得的可读性差不多。把它划成一条线可以更容易地遵循逻辑;水平滚动几乎总是一件坏事,在 &&
运算符处打破它是最可读的方式。
但是,有一种方法可以使其更具可读性:创建一个辅助方法,它可以执行您想要的操作。
private boolean isAorB(YourObject choice) {
return choice == A || choice == B;
}
那么您的 if 语句将是:
if(isAorB(firstChoice) && isAorB(secondChoice)) {
对于未来的读者,包括您自己,这将更具可读性,这正是您真正想要的。
if ((firstChoice == A || firstChoice == B) && (secondChoice == A || secondChoice == B)) {
//do stuff
}
这里要注意的是,当您在脑海中阅读 "firstChoice is equal to A or B" 时,像 (firstChoice == A || B)
这样的东西是有意义的,但对 Java 就没有意义。 || 的左右两边运算符必须评估为布尔值。 'B' 不是布尔类型(我假设),但条件 firstChoice == B
是。
此外,您可以使用圆括号来标记运算顺序,就像处理普通算术一样。即使不需要它们,通常也有助于提高可读性。
正如我在评论中提到的和其他人提到的,没有 shorthand 可以说 "if X equals A or B or C or..." 或类似的东西。你必须说 if (x == a || x == b || x == c)
,等等(COBOL 确实允许这种表达,但不幸的是,这个有用的特性还没有在太多其他语言的设计中找到它的方式。)
你可以说:
if (isOneOf(firstChoice, A, B) || isOneOf(secondChoice, A, B)) {
...
}
如果您像这样定义 isOneOf
方法:
@SuppressWarnings("unchecked")
public static <T> boolean isOneOf(T obj, T... choices) {
for (T choice : choices) {
if (choice.equals(obj)) {
return true;
}
}
return false;
}
[请注意,这允许有两个以上的选择。]