JAVA循环结构 - for, while 及 do...while

有三种主要的循环结构:for循环、while循环、do...while循环。

1.for循环

for循环执行的次数是在执行前就确定的。语法格式如下:

for(初始化; 布尔表达式; 更新) {
    //代码语句
}

说明:
最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
执行一次循环后,更新循环控制变量。
再次检测布尔表达式。循环执行上面的过程。

public class Test {
   public static void main(String args[]) {
 
      int sum = 0;
      for(int x = 0; x < 10; x = x+1) {
         sum++;
      }
      System.out.print("sum = " + sum);  //输出sum = 10
   }
}

for循环的另一种形式

Java5 引入了一种主要用于数组的增强型 for 循环。

for(声明语句 : 表达式) {
   //代码句子
}

声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
表达式:表达式是要访问的数组名,或者是返回值为数组的方法。

public class Test {
   public static void main(String args[]) {
 
      String [] names = {"xiaoming", "xiaohong", "xiaohua", "xiaocao"};
      for(Sting name : names) {
         System.out.print(name); //以次输出名字
      }
   }
}

2.while循环

while( 布尔表达式 ) {
  //循环内容
}

只要布尔表达式为 true,循环就会一直执行下去。

public class Test {
   public static void main(String args[]) {
      int i = 0;
      int sum = 0;
      while( i < 10 ) { //求1+2+...+10的和
         i++;
         sum += i;
      }
   }
}

3.do…while 循环

对于 while 循环而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次。

do {
       //代码语句
}while(布尔表达式);
public class Test {
   public static void main(String args[]) {
      int i = 0;
      int sum = 0;
      do { //求1+2+...+10的和
         i++;
         sum += i;
      }while(i < 10);
   }
}

4.break 关键字

break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块。
break 跳出最里层的循环,并且继续执行该循环下面的语句。

public class Test {
   public static void main(String args[]) {
 
      int count = 0;
      String [] names = {"xiaoming", "xiaohong", "xiaohua", "xiaocao"};
      for(Sting name : names) {
         count++;
         if(count == 3) {
             break;
         }
         System.out.print(name); //输出两个名字就跳出循环语句
      }
   }
}

5.continue 关键字

continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。

public class Test {
   public static void main(String args[]) {
 
      int count = 0;
      String [] names = {"xiaoming", "xiaohong", "xiaohua", "xiaocao"};
      for(Sting name : names) {
         
         if(count%2) {
             continue;
         }
         count++;
         System.out.print(name); //输出下标为偶数的名字
      }
   }
}

你可能感兴趣的:(JAVA循环结构 - for, while 及 do...while)