For循環
- 雖然所有循環結構都可以用while和dowhile表示,但是Java提供了另外一種語句for循環,使一些循環結構變動更加簡單
- for循環語句是支持迭代的一種通用結構,是最有效、最靈活的循環結構
- for循環執行的次數是在執行前就確定的。語法格式如下
for(初始化;布爾表達式;更新){ //代碼語句 }
計算0到100之間的奇數和偶數的和
package struct; public class ForDemo01 { public static void main(String[] args) { int oddSum = 0; int evenSum = 0; for (int i = 0; i <= 100; i++) { if (i%2 != 0){ oddSum+=i; }else { evenSum+=i; } } System.out.println("所有奇數和為:"+oddSum); System.out.println("所有偶數和為:"+evenSum); } }
用while或for循環輸出1-1000之間能被5整除的數,並且每行輸出3個
package struct; public class ForDemo02 { public static void main(String[] args) { for (int i = 0; i <= 1000; i++) { if (i%5 == 0){ System.out.print(i+"\t"); } if (i%(5*3) ==0){ //模為5,取三次換行 System.out.println("\n"); } } //print 輸出完會換行 //println 輸出完不會換行 } }
package struct; public class ForDemo02 { public static void main(String[] args) {//print 輸出完會換行 //println 輸出完不會換行 int j = 0; do { if (j%5 == 0){ System.out.print(j+"\t"); } if (j%(5*3) ==0){ System.out.print("\n"); } j++; }while (j<=1000); } }