一个没有{}的for循环

如果for循环没有{} ,那么该for循环默认对第一条语句进行循环,以;结尾就结束了。这个语法同样适用于if ,while循环。

例如下面这个例子:

public class ForDemo {
	public static void main(String[] args) {
		int MyIntArray[] ={10,20,30,40,50,60,70};
		int s=0;
		for (int i = 0; i < MyIntArray.length; i++) 
			if (i % 2 == 1) 
				s+=MyIntArray[i];
			
		  System.out.println(s);
		 
	}
}

其中

for (int i = 0; i < MyIntArray.length; i++) 
			if (i % 2 == 1) 
				s+=MyIntArray[i];
			
		  System.out.println(s);

等价于

for (int i = 0; i < MyIntArray.length; i++) {
			if (i % 2 == 1) 
				s+=MyIntArray[i];
	      }		
		  System.out.println(s);

猜你喜欢

转载自blog.csdn.net/Nick_zcy/article/details/50812346