For和while的区别

 1 package day03;
 2 
 3 public class ForWhile {
 4     /*for和while的区别:
 5     1、条件控制语句所控制的自增变量因为归属for循环的语法结构中,
 6     for循环结束以后就不能再被访问到了。
 7     2、条件控制语句所控制的自增变量对于while循环来说不归属其语法结构中,
 8     在while循环结束后,该变量还可以继续使用。
 9 
10     * */
11     public static void main(String[] args) {
12         // for循环内部[定义]的变量, 在循环结束后, 就会从内存中消失
13         for (int i = 1; i <=5; i++) {
14             System.out.println(i);
15         }
16         // System.out.println(i);    //  错误: 找不到符号i
17         System.out.println("----------");
18         for (int i = 1; i <=10; i++) {
19             System.out.println(i);
20         }
21 
22         //while循环
23         int a =1;
24         while(a<=5){
25             System.out.println(a);
26             a++;
27         }
28         System.out.println(a+"---");
29     }
30 }

执行结果:

posted @ 2020-12-28 20:45  Eleanor123  阅读(494)  评论(0编辑  收藏  举报