我试图做一些事情:
if (firstChoice == A || B && secondChoice == A || B){
//passes check.
}
逻辑上,如果第一个和第二个选择是A或B,我想要通过。这个语法有效吗?有没有更好的方法呢?
答案 0 :(得分:1)
if (((firstChoice == A) || (firstChoice == B)) && ((secondChoice == A) || secondChoice == B)))
{
//passes check.
}
答案 1 :(得分:1)
你不能== 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)) {
对于未来的读者来说,这将更具可读性,包括你自己,这是你真正想要的。
答案 2 :(得分:0)
if ((firstChoice == A || firstChoice == B) && (secondChoice == A || secondChoice == B)) {
//do stuff
}
这里需要注意的是,(firstChoice == A || B)
之类的内容在您阅读" firstChoice等于A或B"时会有意义。在你的头脑中但它对Java没有意义。 ||的左侧和右侧运算符必须求值为布尔值。 ' B'不是布尔类型(我假设),但条件firstChoice == B
是。
此外,您可以使用括号标记操作顺序,就像使用普通算术一样。即使不需要它们,它通常也有助于提高可读性。
答案 3 :(得分:0)
正如我在评论中提到的那样,其他人已经提到,如果X等于A或B或C或......,则没有简写说明"或类似的东西。你必须说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;
}
[请注意,这允许两个以上的选择。]