在观看基本java的newbostons教程时,他教我们做if if这样的语句.(注意花括号)
if("pie"== "pie"){
System.out.println("Hurrah!");
}
Run Code Online (Sandbox Code Playgroud)
所以我尝试去除花括号
if("pie"== "pie")
System.out.println("Hurrah!");
Run Code Online (Sandbox Code Playgroud)
它仍然有效!由于我是java的新手,我不知道为什么会这样.我想知道删除(或添加)花括号是否有任何好处/缺点.
是否可以在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)
但我得到的错误就像"在其他方面的语法令牌,删除此令牌"和"其他无法解决的真实其他".
我究竟做错了什么?