嵌套循環
嵌套循環案例二
需求:請輸出下列的形狀
*
**
***
****
*****
思路講解:通過簡單的觀察,我們看到這是一個行是5,列數是變化的形狀
列數是如何變化的呢?
第一行:1列 y=0,y<=0,y++
第二行:2列 y=0,y<=1,y++
第三行:3列 y=0,y<=2,y++
第四行:4列 y=0,y<=3,y++
第五行:5列 y=0,y<=4,y++
在看外循環x的變化,恰好就是x=0,1,2,3,4
外循環控制行數,內循環控制列數.
public class ForDemo1 {
public static void main(String[] args) {
for (int i = 0; i <5 ; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
嵌套循環案例三:
需求:在控制檯輸出九九乘法表。
思路:首先我們寫出九九乘法表:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
...
1*9=9 2*9=18 3*9=27 ...
我們先把這個九九乘法表看出是這樣的一個形狀:
*
**
***
****
*****
******
*******
********
*********
注意:
'\x' x表示任意,這種做法叫轉移字符。
'\t' tab鍵的位置
'\r' 回車
'\n' 換行
public class ForForDemo3 {
public static void main(String[] args) {
for (int x = 1; x <= 9; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + "*" + x + "=" + y * x + "\t");
}
System.out.println();
}
}
}