gpt4 book ai didi

java - 从 java 中的 If 语句中删除花括号是否有区别

转载 作者:IT老高 更新时间:2023-10-28 20:44:13 26 4
gpt4 key购买 nike

在观看 newbostons 的基本 java 教程时,他教我们做这样的 if 语句。(注意花括号)

if("pie"== "pie"){
System.out.println("Hurrah!");
}

所以我试着去掉花括号

if("pie"== "pie")
System.out.println("Hurrah!");

它仍然有效!由于我是java新手,我不知道为什么会这样。而且我想知道删除(或添加)花括号是否有任何好处/坏处。

最佳答案

对于单个语句,它将保持不变,但如果您想在 if block 中组合多个语句,则必须使用花括号。

if("pie"== "pie"){
System.out.println("Hurrah!");
System.out.println("Hurrah!2");
}

if("pie"== "pie")
System.out.println("Hurrah!"); //without braces only this statement will fall under if
System.out.println("Hurrah!2"); //not this one

您应该看到:Blocks in Java

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use of blocks:

class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}

(来自上述链接的示例)

关于java - 从 java 中的 If 语句中删除花括号是否有区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15786949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com