1.Java中循环有三种(作用:不断重复执行一些程序代码,但是有判断条件,目的就是终止循环的判断)

 while

 do..while

 For

 

2.while循环

 语法:

while (判断条件) { //判断条件接收的是一个布尔类型值

   //程序代码

}

 while循环执行的流程

  • 首先判断while中条件
  • 如果while中条件接收的布尔类型的值为true, 则执行循环体中的代码
  • 如果执行循环体中代码一旦结束,则继续回到while条件进行判断
  • 否则如果条件中的布尔类型值为false,则循环结束

举例

 

 1 package com.gsa.day3;
 2 
 3 public class WhileSample {
 4     
 5     public static void main(String[] args) {
 6         int i = 0;
 7         while(true) {
 8             System.out.println(++i);
 9             if (i == 10000) {
10                 /**
11                  * break作用
12                  * 1. 跳出switch语句
13                  * 2. 跳出循环
14                  */
15                 break;
16             }
17         }
18     }
19     
20 }

 

 

3.do..while

 语法:

do {

} while(判断条件);

 执行流程

  • 程序先执行循环体中程序,再判断循环条件
  • 如果循环条件的布尔值为true,继续执行循环体内中的代码
  • 否则结束循环

 

 

案例

 

 1 package com.gsa.day3;
 2 
 3 public class DoWhileSample {
 4 
 5     public static void main(String[] args) {
 6         int i = 0;
 7         do {
 8             System.out.println(++i);
 9             if (i == 10000) {
10                 break;
11             }
12         } while(true);
13     }
14     
15 }

 

 

 

4.for循环

 

 语法

 

for (初始值;  条件判断;  增量) {

 

  //程序代码

 

}

 

 执行流程

 

  • 程序进入for循环之前会先执行for循环中的初始值的设置(初始值其实就是需要定义一个变量)
  • 接着程序会进行for循环中条件的判断(布尔类型值的判断)。如果为true执行循环体如果为false则循环结束
  • 执行for循环中的程序代码
  • 最后执行初始值的增量变化
  • 执行完增量变化,程序会再次执行循环条件判断,不会执行初始值的设置

 

案例:

 1 package com.gSa.day3;
 2 
 3 public class ForSample {
 4     
 5     public static void main(String[] args) {
 6         
 7         for (int i = 0; i < 10000; i++) {
 8             System.out.println(i);
 9         }
10     }
11 }

5.加强对for循环语法定义的认识

 本身for (初始化值条件增量) {}  常规语法定义

 想想让for循环变为死循环

for (;;) { //死循环的写法

}

 for循环中不给定初始变量

int i = 0;

for (; i < 10000; i++) {

}

 for循环中的初始变量只能供循环体内的代码使用

 

package com.gSa.day3;

public class ForSample {
	
	public static void main(String[] args) {
		
		for (int i = 0; i < 10000; i++) {
			System.out.println(i);
		}
		
		/**
		 * 变量的作用域
		 * 1. 全局变量, 在定义的类中任何地方都会使用
		 * 2. 局部变量, 只能在方法或者语句块使用
		 */
		System.out.println(i); //代码错误, 因为i不可用
	}
}

 

 

 

 

package com.gxa.day3;

 

public class ForSample {

 

public static void main(String[] args) {

 

for (int i = 0; i < 10000; i++) {

System.out.println(i);

}

 

/**

 * 变量的作用域

 * 1. 全局变量在定义的类中任何地方都会使用

 * 2. 局部变量只能在方法或者语句块使用

 */

System.out.println(i); //代码错误因为i不可用

}

}

posted on 2016-03-30 19:43  Oliver·Keene  阅读(141)  评论(0)    收藏  举报