Java 中的 1 行 IF 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/504003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
1-line IF statements in java
提问by Click Upvote
Is it possible to have IF statements without braces in Java, e.g:
是否可以在 Java 中使用不带大括号的 IF 语句,例如:
if (x == y)
z = x * y;
else
z = y - x;
It's possible in PHP, and I'm not sure if I'm doing something wrong.
这在 PHP 中是可能的,我不确定我是否做错了什么。
Clarification:Here's my actual code that i'm using:
澄清:这是我正在使用的实际代码:
if (other instanceof Square)
Square realOther = (Square) other;
else
Rectangle realOther = (Rectangle) other;
But i got errors like "Syntax token on realOther , delete this token" and "realOther cannot be resolved" among others.
但是我遇到了诸如“realOther 上的语法标记,删除此标记”和“realOther 无法解析”等错误。
What am I doing wrong?
我究竟做错了什么?
采纳答案by Sean Bright
Yes, you can follow an if
statement with a single statement without using curly braces (but do you really want to?), but your problem is more subtle. Try changing:
是的,您可以在if
不使用花括号的情况下使用单个语句跟随语句(但您真的想要吗?),但您的问题更微妙。尝试改变:
if (x=y)
to:
到:
if (x==y)
Some languages (like PHP, for example) treat any non-zero value as true and zero (or NULL
, null
, nil
, whatever) as false
, so assignment operations in conditionals work. Java only allows boolean expressions (expressions that return or evaluate to a boolean) inside conditional statements. You're seeing this error because the result of (x=y)
is the value of y
, not true
or false
.
某些语言(例如 PHP)将任何非零值视为真值,将零(或NULL
, null
,nil
等)视为false
,因此条件中的赋值操作有效。Java 只允许在条件语句中使用布尔表达式(返回或计算为布尔值的表达式)。您看到此错误是因为 的结果(x=y)
是 的值y
,而不是true
或false
。
You can see this in action with this simple example:
你可以通过这个简单的例子看到这一点:
if (1)
System.out.println("It's true");
if (true)
System.out.println("It's true");
The first statement will cause compilation to fail because 1
cannot be converted to a boolean.
第一条语句将导致编译失败,因为1
无法转换为布尔值。
Edit:My guess on your updated example (which you should have put in the question and not as a new answer) is that you are trying to access realOther
after you assign it in those statements. This will not work as the scope of realOther
is limited to the if
/else
statement. You need to either move the declaration of realOther
above your if
statement (which would be useless in this case), or put more logic in your if
statement):
编辑:我对你更新的例子的猜测(你应该把它放在问题中而不是作为新答案)是你realOther
在这些语句中分配它后试图访问。这将不起作用,因为范围realOther
仅限于if
/else
语句。您需要将声明移动到realOther
您的if
语句上方(在这种情况下这将是无用的),或者在您的if
语句中添加更多逻辑):
if (other instanceof Square)
((Square) other).doSomething();
else
((Rectangle) other).doSomethingElse();
To assist further we would need to see more of your actualcode.
为了进一步提供帮助,我们需要查看更多您的实际代码。
Edit:Using the following code results in the same errors you are seeing (compiling with gcj
):
编辑:使用以下代码会导致您看到的相同错误(使用 编译gcj
):
public class Test {
public static void Main(String [] args) {
Object other = new Square();
if (other instanceof Square)
Square realOther = (Square) other;
else
Rectangle realOther = (Rectangle) other;
return;
}
}
class Rectangle {
public Rectangle() { }
public void doSomethingElse() {
System.out.println("Something");
}
}
class Square {
public Square() { }
public void doSomething() {
System.out.println("Something");
}
}
Note that adding curly braces to that if
/else
statement reduces the error to a warning about unused variables. Our own mmyerspoints out:
请注意,向该if
/else
语句添加大括号会将错误减少为有关未使用变量的警告。我们自己的mmyers指出:
http://java.sun.com/docs/books/jls/third_edition/html/statements.htmlsays: "Every local variable declaration statement is immediately contained by a block." The ones in the
if
statement don't have braces around them, therefore they aren't in a block.
http://java.sun.com/docs/books/jls/third_edition/html/statements.html说:“每个局部变量声明语句都立即包含在一个块中。”
if
语句中的那些在 它们周围没有大括号,因此它们不在块中。
Also note that my other example:
还要注意我的另一个例子:
((Square) other).doSomething()
compiles without error.
编译没有错误。
Edit:But I think we have established (while this is an interesting dive into obscure edge cases) that whatever you are trying to do, you are not doing it correctly. So what are you actuallytrying to do?
编辑:但我认为我们已经确定(虽然这是对模糊边缘情况的有趣深入研究),无论您尝试做什么,都没有正确执行。那么你究竟想做什么?
回答by Yuval Adam
Yes, but you need to keep the semi colon between the if-else, like so:
是的,但您需要在 if-else 之间保留分号,如下所示:
if (true) System.out.println("true"); else System.out.println("false");
Also, make sure you fix your comparison operator to be ==
.
另外,请确保将比较运算符修复为==
.
回答by William Brendel
The following code islegal:
以下代码是合法的:
int x = 5;
int y = 2;
int z = 0;
if (x == y)
z = x * y;
else
z = y - x;
As Sean Bright mentioned, your problem is that you are trying to test a non-boolean expression. You should be using the ==
operator instead of the =
operator in your if
clause.
正如 Sean Bright 所提到的,您的问题是您正在尝试测试非布尔表达式。您应该在子句中使用==
运算符而不是=
运算符if
。
Another thing to mention is that it is considered, by many, bad practice to skip using the curly braces in an if-then-else
statement. It can lead to errors down the road, such as adding another statement to the body of the if
or else
code blocks. It's the type of bug that might be a pain to figure out.
另一件事要提到的是,许多人认为在if-then-else
语句中跳过使用大括号是不好的做法。它可能会导致错误,例如在if
或else
代码块的主体中添加另一条语句。这是一种可能很难弄清楚的错误类型。
This isn't really an issue when using an if-else
statement, because Java will catch this as a syntactic error (else
statement without a preceding if
). However, consider the following if
statement:
这在使用if-else
语句时并不是真正的问题,因为 Java 会将其作为语法错误(else
没有前面的语句if
)捕获。但是,请考虑以下if
语句:
if (x == y)
z = y * x;
Now, suppose later on you need to do more things if x == y
. You could easily do the following without realizing the error.
现在,假设稍后您需要做更多的事情,如果x == y
. 您可以轻松地执行以下操作而不会意识到错误。
if (x == y)
z = y * x;
w = x * y - 5;
Of course, the second statement w = x * y - 5
will be executed regardless of the outcome of the if
statement test. If you had curly braces to begin with, you would have avoided the problem.
当然,w = x * y - 5
无论if
语句测试的结果如何,都会执行第二条语句。如果您一开始就使用花括号,您就可以避免这个问题。
if (x == y) {
z = y * x;
w = x * y - 5; // this is obviously inside the if statement now
}
回答by Joachim Sauer
It is possible (apart from the typo/bug that @Sean pointed out), but depending on the code guidelines you follow it's considered bad form.
这是可能的(除了@Sean 指出的错别字/错误),但根据您遵循的代码指南,它被认为是错误的形式。
The code guidelines that I usually follow (both at work and for private projects where I decide) forbids single statements without a block (i.e. every if/while/for needs a block).
我通常遵循的代码指南(在工作中和我决定的私人项目中)禁止没有块的单个语句(即每个 if/while/for 都需要一个块)。
回答by Todd R
Just because you can do something doesn't mean you should.
仅仅因为你可以做某事并不意味着你应该做。
Consider what happens when you add logging:
考虑添加日志记录时会发生什么:
if (x==y)
z=x*y;
else
System.out.println("Values weren't equal);
z=y-x;
Surprise! "z" will never equal x * y. While you may think that leaving the brackets out makes your code more readable, it makes it much less safe. I only say this because I've had to troubleshoot tons of code that has this same defect.
惊喜!“z”永远不会等于 x * y。虽然您可能认为不使用括号会使您的代码更具可读性,但它会降低安全性。我之所以这么说是因为我不得不对大量具有相同缺陷的代码进行故障排除。
回答by eleven81
Always consult the Code Conventions for the JavaTM Programming Language:
始终查阅JavaTM 编程语言的代码约定:
Specifically, see Chapter 7, Section 4:
具体见第7章第4节:
Note:if statements always use braces {}. Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES {}! statement;
注意:if 语句总是使用大括号 {}。避免以下容易出错的形式:
if (condition) //AVOID! THIS OMITS THE BRACES {}! statement;
回答by John Nilsson
If you want a one liner if that is an expression you can use the terniary operator
如果你想要一个单线,如果那是一个表达式,你可以使用三元运算符
final int myVal = predicate ? consequent : alternative;
which is roughly the same as
这与
final int myVal;
if(predicate)
myVal = consequent;
else
myVal = alternative;
回答by Paul Tomblin
I always use braces because some languages allow them and some don't, and I can never keep them straight. Maybe I'm too old, or maybe I know too many languages.
我总是使用大括号,因为有些语言允许它们,有些则不允许,而且我永远无法保持它们的正直。也许我太老了,或者我知道太多的语言。
回答by Bill K
Edit: To be more clear, this is your problem:
编辑:更清楚地说,这是你的问题:
This:
这个:
if (other instanceof Square)
Square realOther = (Square) other;
else
Rectangle realOther = (Rectangle) other;
is the exact same thing as this:
与此完全相同:
if (other instanceof Square) {
Square realOther = (Square) other;
} else {
Rectangle realOther = (Rectangle) other;
}
Notice that you never do anything with realOther. You define it there, but since it's scoped to that set of braces, you throw it away as soon as hitting the closing brace.
请注意,您从不使用 realOther 做任何事情。你在那里定义它,但因为它的范围是那组大括号,你一碰到右大括号就扔掉它。
Not including the braces doesn't help, the fact that it's a statement (after an if) makes it an independent code block, as soon as that block exits, "realOther" is discarded.
不包括大括号无济于事,事实上它是一个语句(在 if 之后)使它成为一个独立的代码块,一旦该块退出,“realOther”就会被丢弃。
Java recognizes that this is the case and tells you (To sloppily quote Inigo Montoya) "I don't think that means what you think it means" .
Java 认识到情况确实如此,并告诉您(草率地引用 Inigo Montoya 的话)“我认为这不是您认为的意思”。
Secondary problem, Java is strongly typed. Even if it might allow syntax like you are saying, right after this if statement, it has to have an absolute final type for realOther. Your if statement would completely break java's brain because it wouldn't know if realOther was supposed to be treated as a rectangle or a square.
次要问题,Java 是强类型的。即使它可能允许像您说的那样语法,在此 if 语句之后,它也必须具有 realOther 的绝对最终类型。您的 if 语句会完全破坏 java 的大脑,因为它不知道 realOther 是否应该被视为矩形或正方形。
Suppose rectangle had a setWidth and setHeight method (and square just had a setHeight). After this IF statement, should Java allow you to call setWidth or not? Java MUST know these things at compile time (if not, we wouldn't need casting).
假设矩形有一个 setWidth 和 setHeight 方法(而正方形只有一个 setHeight)。在这个 IF 语句之后,Java 应该允许你调用 setWidth 还是不允许?Java 必须在编译时知道这些事情(如果没有,我们就不需要强制转换)。
another edit:
另一个编辑:
To fix it, you use this:
要修复它,您可以使用以下命令:
// class Rectangle extends Square
// Both implement setHeight, Rect also implements setWidth.
public void reSize(Square other, int h, int w) {
other.setHeight(h);
if (realOther instanceof Rectangle) {
((Rectangle)realOther).setWidth(w);
}
In other words, the way you're supposed to work with related objects is to leave them as the more abstract object for as long as possible, only using the specific objects when you need to call a method on that object.
换句话说,您应该使用相关对象的方式是尽可能长时间地将它们作为更抽象的对象,仅在需要调用该对象上的方法时才使用特定对象。
If you code it right, you can almost always use the more abstract and rarely use the specific. With square and rect, this isn't obvious, square/rect is a pretty sloppy problem and is used as an example of some tough decisions you have to make with OO programming, but it really does work out nearly all the time--I very rarely have to cast at all...
如果你编码正确,你几乎总是可以使用更抽象的,而很少使用具体的。对于 square 和 rect,这并不明显,square/rect 是一个相当草率的问题,被用作使用 OO 编程必须做出的一些艰难决定的示例,但它确实几乎所有时间都有效——我很少需要投...
回答by Zachery Delafosse
I must agree with Bill K... "You cannot say "Square realOther" in an if statement because you are declaring it within the scope of that single line of code, it would vanish at the end of the if statement."
我必须同意 Bill K...“你不能在 if 语句中说“Square realOther”,因为你是在单行代码的范围内声明它,它会在 if 语句的末尾消失。
Consider defining realOther beforehand as an Object, then simply assigning realOther with the = (Square) other; / = (Rectangle) other;
考虑事先将 realOther 定义为一个对象,然后简单地用 = (Square) other 分配 realOther;/ =(矩形)其他;
Locality is your problem, though.
不过,位置是你的问题。