简单的for 循环,可以初始化变量,检查条件和增加、减少变量的值。
语法:
for (initialization; condition; incr/decr){ //code通被executed }
实例:
package day02;
public class Test12 {
/**
* @param args
* @author bindu
*/
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
for-each 循环:
package day02; public class Test12 { /** * @param args * @author bindu */ public static void main(String[] args) { int attr[] = {12,22,33,34,56,66,78}; for (int i: attr){ System.out.println(i); } } }
标记for 循环:
package day02; public class Test12 { /** * @param args * @author bindu */ public static void main(String[] args) { aa: for(int i =1;i<=3;i++){ bb:for(int j = 1;j<=3;j++){ if (i ==2&& j==2){ break aa; } System.out.println(i +" "+j); } } } }
无限for循环:
package day02; public class Test12 { /** * @param args * @author bindu */ public static void main(String[] args) { for (;;){ System.out.println("这就是死循环啊!"); } } }
求1!+2!+3!+...10!的和:
package homework; public class Test10 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int sum =0; int times =1; for(int i =1;i<=10;i++){ times*=i; sum+=times; } System.out.println("1!+2!+....10!="+sum); } }
打印菱形:
package homework; public class Test11 { /** * @param args */ public static void main(String[] args) { // 打印菱形 int ceng = 5; for (int i = 0; i < ceng; i++) { for (int j = 0; j < ceng-i-1; j++) { System.out.print(" "); } for (int k = 0; k < 2*i+1; k++) { System.out.print("*"); } System.out.println(""); } for (int i = 0; i < ceng-1; i++) { for (int j = 0; j < i+1; j++) { System.out.print(" "); } for (int k = 0; k < 2*(ceng-i-2)+1; k++) { System.out.print("*"); } System.out.println(""); } } }