for 循环 大圈套小圈
#1.1for循环思想
1 2 3 4 5 6 7 8 9
| public class code4 { public static void main(String[] args) { for (int x = 0; x < 3; x++) { for (int y = 0; y < 4; y++) { System.out.println("ok"); } } } }
|

读第一个for循环初始化一个x 变量x=0:
先执行x=0; 执行x<3满足条件—>
执行第二个for循环语句初始化一个变量y=0;
先执行y=0;执行y<4满足条件–>打印一次ok
当内循环没有结束时循环出不去执行–>y++;打印四次ok;
y++=4时候y<4不成立 跳出循环 y在内存中消失 –>执行–x++
满足条件 又产生一个y=0,内循环继续循环四次 所以一共打印12个ok

#1.2验证doc命令行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class code5 {
public static void main(String[] args) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { System.out.print("*"); } System.out.println(); } } }
|

i 控制行 第一个for循环
j控制列 第二个for循环 (每一列的个数)
#1.3验证doc命令行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class code6 {
public static void main(String[] args) { for (int i = 0; i < 5; i++) { for (int j = i; j < 5; j++) { System.out.print("*"); } System.out.println(); } } }
|

分析:



#1.4验证doc
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class code7 {
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.5验证doc⭐️
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class code8 {
public static void main(String[] args) { for (int i = 0; i < 5; i++) { for (int j = 5; j > i; j--) { System.out.print(j); } System.out.println(); } } }
|


int j=5 j>i j– 其中j—是关键
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class code9 {
public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <=i; j++) { System.out.print(i); } System.out.println(); } } }
|


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class code10 {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(" "); } for (int z = i; z<=5 ; z++) { System.out.print("* "); }System.out.println(); }
} }
|

分析:

#1.6作 业:打印


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class code8 {
public static void main(String[] args) { for (int i = 0; i < 5; i++) { for (int j = 5; j >i; j--) { System.out.print(j); }System.out.println(); } } }
|
分析:


规律:for内循环 如果j<i 不成立 改成j>i 并且让j–

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class code9 {
public static void main(String[] args) { for (int i = 1; i <=5; i++) { for (int j = 0; j < i; j++) { System.out.print(i); }System.out.println(); } } }
|
Author:
John Doe
Permalink:
http://yoursite.com/2018/12/15/java基础/for循环讲解/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE
Slogan:
Do you believe in DESTINY?