0

假设我下面的代码仅使用 2 个大括号:

public void listFish(){
System.out.println(name + " with " + numFishCaught + " fish as follows: ");
for (Fish f: fishCaught)
    if (f != null)
    System.out.println(f.toString());}

如果我这样重写它会伤害我的代码或改变它的运行方式吗?使用大括号的正确方法通常是什么?谢谢

public void listFish(){
System.out.println(name + " with " + numFishCaught + " fish as follows: ");
for (Fish f: fishCaught){
    if (f != null){
    System.out.println(f.toString());
    }
}     } 
4

3 回答 3

1

不,它不会“伤害”您的代码。实际上,好的做法是始终使用大括号。解释一下 - 找出这四个之间的区别:

if (2 == 2)
    System.out.println("First line");
    System.out.println("Second line");


if (2 == 2)
    System.out.println("First line");
System.out.println("Second line");


if (2 == 2) {
    System.out.println("First line");
    System.out.println("Second line");
}


if (2 == 2){
    System.out.println("First line");
}
System.out.println("Second line");

使用花括号时,一切都一目了然。

于 2014-04-08T19:37:55.633 回答
1

对于单个语句,它将保持不变,但是如果您想在 if 块中对多个语句进行分组,那么您必须使用正确的大括号。

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

你应该看到:

块是一组位于平衡大括号之间的零个或多个语句,可以在任何允许使用单个语句的地方使用。以下示例 BlockDemo 说明了块的使用:

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
     }
}
于 2014-04-08T19:21:44.070 回答
1

通常,当您创建任何类型的循环并且只有一行代码(即只有一个以分号结尾的语句)时,您不需要{花括号}。但是,当进入循环时要执行多行时,请使用 {curly-braces} ,如下所示:

public void listFish () {
    System.out.println( name + " with " + numFishCaught + " fish as follows: " );
        for ( Fish f: fishCaught ) {
            if ( f != null ) {
                System.out.println( f.toString() );
            }
        }
}

代码就是它是否可以运行......我可以如下重写代码,它仍然可以完美运行:

public void listFish () { System.out.println( name + " with " + numFishCaught + " fish as follows: " ); for ( Fish f: fishCaught ) { if ( f != null ) { System.out.println( f.toString() ); } } }

排列大括号和其他东西的全部目的是为了可读性......如果你能读懂它,你通常很高兴!

于 2014-04-08T19:22:27.210 回答