學習目標:
掌握 for 循環的使用學習內容:
1、for語法
for(初始化語句; boolean表達式; 循環后操作語句) {
循環體;
}
流程圖如下:
特點:
初始化語句:只在循環開始時執行一次,一般是定義一個變量,並賦值。
boolean表達式:表達式為false時,循環終止,為true,才執行循環體。
循環后操作語句:循環體執行后會調用該語句,一般是變量的遞增或遞減操作。
執行順序:
①、初始化語句->②、boolean表達式:
若為false:跳過本次循環,執行去其他語句
若為true:③、執行循環體->④、循環后操作語句->②、boolean表達式(依次循環知道跳過所有循環)。
需求:輸出1~100整數之和
代碼如下:
System.out.println("begin...");
int total = 0;
//最終之和,初始為0
for (int count = 1; count < 101; count++) {
total = total + count;
}
System.out.println(total);
System.out.println("ending...");
運行效果:
begin...
5050
ending...
Process finished with exit code 0
2、循環嵌套
循環解決的是:某一個操作需要重復執行,如果一個重復的操作需要做N次,此時得使用嵌套循環。
需求:打印直角三角形
代碼如下:
for (int line = 1; line <= 5; line++) {
for (int i = 1; i <= line; i++) {
System.out.print("*");
}
System.out.println();
}
運行效果:
*
**
***
****
*****
Process finished with exit code 0
總結:
for循環必須熟練掌握,需要練習for 循環可以看我的JavaSE小例題