是否可以在Java中使用没有大括号的IF语句,例如:
if (x == y)
z = x * y;
else
z = y - x;
Run Code Online (Sandbox Code Playgroud)
这在PHP中是可能的,我不确定我是否做错了什么.
澄清:这是我正在使用的实际代码:
if (other instanceof Square)
Square realOther = (Square) other;
else
Rectangle realOther = (Rectangle) other;
Run Code Online (Sandbox Code Playgroud)
但我得到的错误就像"在其他方面的语法令牌,删除此令牌"和"其他无法解决的真实其他".
我究竟做错了什么?
Sea*_*ght 18
是的,您可以if使用单个语句跟随语句而不使用花括号(但您真的想要吗?),但您的问题更加微妙.尝试改变:
if (x=y)
Run Code Online (Sandbox Code Playgroud)
至:
if (x==y)
Run Code Online (Sandbox Code Playgroud)
有些语言(如PHP,例如)治疗任何非零值作为真和零(或NULL,null,nil,等等)的false,所以在条件句工作任务操作.Java只允许在条件语句中使用布尔表达式(返回或求值为布尔值的表达式).你看到这个错误是因为结果(x=y)是值y,而不是true或false.
您可以通过以下简单示例看到这一点:
if (1)
System.out.println("It's true");
if (true)
System.out.println("It's true");
Run Code Online (Sandbox Code Playgroud)
第一个语句将导致编译失败,因为1无法转换为布尔值.
编辑:我对您更新的示例(您应该在问题中提出而不是作为新答案)的猜测是您realOther在这些语句中分配后尝试访问.这不起作用,因为范围realOther仅限于if/ elsestatement.您需要移动语句realOther上方的if声明(在这种情况下这将是无用的),或者在if语句中添加更多逻辑):
if (other instanceof Square)
((Square) other).doSomething();
else
((Rectangle) other).doSomethingElse();
Run Code Online (Sandbox Code Playgroud)
为了进一步提供帮助,我们需要查看更多您的实际代码.
编辑:使用以下代码会导致您看到的相同错误(编译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");
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,向该if/ else语句添加花括号可将错误减少为有关未使用变量的警告.我们自己的mmyers指出:
http://java.sun.com/docs/books/jls/third_edition/html/statements.html 说:"每个局部变量声明语句都会立即被一个块包含." 在的那些
if说法没有他们周围的括号,因此他们不是在一个块.
另请注意我的另一个例子:
((Square) other).doSomething()
Run Code Online (Sandbox Code Playgroud)
编译没有错误.
编辑:但我认为我们已经建立了(虽然这是一个有趣的潜入晦涩的边缘情况),无论你想做什么,你都没有正确地做到这一点.那么你究竟想做什么?
| 归档时间: |
|
| 查看次数: |
21445 次 |
| 最近记录: |