Java之if中的代码块是否要省略的一点点建议

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cadi2011/article/details/51744459

1、不建议省略if的语句块,虽说只有if下面只有一条语句,可以省略代码块。看下下面的例子!还用到了foreach语法……,省略了语句块,容易坑自己!!!

	public static void main(String args[]) {
		int[] temps = {5, 5, 6, 6};
		if (true) for (int i: temps) {
			System.out.println(i);
		}
		
		if (true)
			System.out.println("fk");
		else 
			System.out.println("else fk");
	}

2、加上语句块,让出错减少

public class ForTest {
	public static void main(String args[]) {
		int[] temps = {5, 5, 6, 6};
		
		if (true) {
			for (int i: temps) {
				System.out.println(i);
			}
		}
		
		if (true) {
		System.out.println("fk");
		}else {
			System.out.println("else fk");
		}
	}
}

猜你喜欢

转载自blog.csdn.net/cadi2011/article/details/51744459