是否可以在 Java 中使用不带大括号的 IF 语句,例如:
if (x == y)
z = x * y;
else
z = y - x;
这在 PHP 中是可能的,我不确定我是否做错了什么。
澄清:这是我正在使用的实际代码:
if (other instanceof Square)
Square realOther = (Square) other;
else
Rectangle realOther = (Rectangle) other;
但我遇到了诸如“realOther 上的语法标记,删除此标记”和“realOther 无法解析”等错误。
我做错了什么?
最佳答案
是的,您可以在 if
语句后跟一个语句而不使用大括号(但您真的想要吗?),但您的问题更加微妙。尝试更改:
if (x=y)
到:
if (x==y)
某些语言(例如 PHP)将任何非零值视为真和零(或 NULL
、null
、nil
, whatever) 为 false
,因此条件语句中的赋值操作有效。 Java 只允许在条件语句中使用 boolean 表达式(返回或计算为 boolean 值的表达式)。您看到此错误是因为 (x=y)
的结果是 y
的值,而不是 true
或 false
.
你可以通过这个简单的例子看到这一点:
if (1)
System.out.println("It's true");
if (true)
System.out.println("It's true");
第一条语句将导致编译失败,因为 1
无法转换为 boolean 值。
编辑:我对您更新后的示例的猜测(您应该将其放入问题中而不是作为新答案)是您试图在之后访问 realOther
您在这些语句中分配它。这将不起作用,因为 realOther
的范围仅限于 if
/else
语句。您需要将 realOther
的声明移到您的 if
语句之上(在这种情况下这将毫无用处),或者在您的 if
中放置更多逻辑> 声明):
if (other instanceof Square)
((Square) other).doSomething();
else
((Rectangle) other).doSomethingElse();
为了进一步提供帮助,我们需要查看更多您的实际代码。
编辑:使用以下代码会导致您看到的相同错误(使用 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");
}
}
请注意,在 if
/else
语句中添加花括号可将错误减少为有关未使用变量的警告。我们自己的mmyers指出:
http://java.sun.com/docs/books/jls/third_edition/html/statements.html says: "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.
另请注意我的另一个示例:
((Square) other).doSomething()
编译没有错误。
编辑:但我认为我们已经确定(虽然这是对晦涩的边缘情况的有趣深入研究)无论您尝试做什么,您都没有正确地做。那么你实际上想做什么?
关于java - Java 中的 1 行 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/504003/