Java 循环结构

for 循环

for循环执行的次数是在执行前就确定的。

说明:

  • 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
  • 然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
  • 执行一次循环后,更新循环控制变量。
  • 再次检测布尔表达式。循环执行上面的过程。
/*格式
for(初始化; 布尔表达式; 更新) {
    //代码语句
}
*/
public class Test {
   public static void main(String args[]) {
      for(int x = 0; x < 5; x++) {
         System.out.println("value of x : " + x );
      }
   }
}

运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4

例子

九九乘法表

/*
九九乘法表
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
*/
class  Test{
	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+"	");
			}
			System.out.println();
		}
	}
}

* 图标

/*
    * 
   * *
  * * *
 * * * * 
* * * * * 
 * * * *
  * * * 
   * *
    * 
*/

class  Test{
	public static void main(String[] args) {
		for (int x = 0; x < 5; x++ ){//外循环控制行数。		
			for(int y = x + 1; y < 5; y++){//外循环控制列数。
				System.out.print(" ");
			}
			for(int z = 0; z <= x; z++){
				System.out.print("* ");
			}
			System.out.println();
		}
		for (int x = 0; x < 4; x++ ){		
			for(int y = 0; y <= x; y++){
				System.out.print(" ");
			}
			for(int z = 4; z > x; z--){
				System.out.print("* ");
			}
			System.out.println();
		}
	}
}

while 循环

  • 只要布尔表达式为 true,循环就会一直执行下去
/*格式
while(布尔表达式){
  //循环内容
}
*/
public class Test {
   public static void main(String args[]) {
      int x = 0;
      while( x < 5 ) {
         System.out.println("value of x : " + x );
         x++;
      }
   }
}

运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4


无限循环的最简单表现形式

for(;;){}
while(true){}

do while 循环

  • 即使不满足条件,也至少执行一次
/*格式
do{
   //代码语句
}while(布尔表达式);
*/
public class Test {
   public static void main(String args[]){
      int x = 0;
      do{
         System.out.println("value of x : " + x );
         x++;
      }while( x < 5 );
   }
}

运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4


break 关键字

主要用于循环语句或者 switch 语句中,用来跳出整个语句块。

/*格式
break;//加入这句语句
*/
public class Test {
   public static void main(String args[]){
      for(int x = 0; x < 10; x++){
         if( x == 5 ){
            break;
         }
         else{}
         System.out.println("value of x : " + x);
      }
   }
}

运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4


continue 关键字

主要用于让程序立刻跳转到下一次循环的迭代。

  • 在 for 循环中,continue 语句使程序立即跳转到更新语句。
  • 在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句
public class Test {
   public static void main(String args[]){
      for(int x = 0; x < 5; x++){
         if( x == 2 ){
            continue;
         }
         else{}
         System.out.println("value of x : " + x);
      }
   }
}

运行结果:
value of x : 0
value of x : 1
value of x : 3
value of x : 4

原文地址:https://www.cnblogs.com/hen-java/p/12599007.html