Java流程控制:循环语句

当条件表达式的返回值为真时则执行“{}”中的语句,当执行完了“{}”中的语句,重新判断条件表达式的返回值,直到表达式返回的结果为假时,退出循环

if与while的区别就是,if只执行和判断一次而while是视情况而定如果符合条件将会一直执行。

for循环与while循环的区别是for是循环次数是已知的,而while的循环次数是未知的

do while:适合于循环至少执行一次的。最好选择do while循环先执行后判断

接下来我们做个小实验,用while来进行计算1到10之内计算

public class Demo {

 public static void main(String[] args) {
      int x=1; //定义int类型X为1
      int sum=0;定义sum为int类型赋值为0
       while(x<=10){定义while循环x<10
        sum=sum+x;     //0+1
        x++;//2
           System.out.println(x);//输出从2开始循环相加
        System.out.println(sum); //
       }
       System.out.println("sum="+sum);//计算以上公式的总和
 }

}

执行结果为:2
1
3
3
4
6
5
10
6
15
7
21
8
28
9
36
10
45
11
55
sum=55

do......while

先执行再判断

扫描二维码关注公众号,回复: 1830668 查看本文章

做一下试验来看它和while语句的区别

public class Cycle {
    public static void main(String[] args) {
  int a=100;
  while(a==60){
   System.out.println("ok1");
   a--;
  }
  int b=100;
  do{//先执行后判断,所以输出了ok2
   System.out.println("ok2");
   b--;
  }while(b==60);
 }
}

执行结果:ok2

for循环:for是循环次数是已知的,可执行某条语句知道某个条件满足。

我们尝试一下2到100之内所有偶数相加的和

public class Circulate {

 public static void main(String[] args) {
  int sum=0;
  for(int i=2;i<=100;i+=2){ //for循环内int定义为2,i<=100
                         //是指从2开始循环到100包括100
                         //i+=2就是4
   sum=sum+i;//sum的赋值是0+2=2;
  }
  //将输出结果输出
          System.out.println("2-100之间的所有偶数之和为"+sum);
 }

}

foreach也就是增强for,是java5新增加的语法

用增强for来计算一下2~100之间偶数的和

public class Repetiton {
  public static void main(String[] args) {
 int arr[]={7,10,1};//设置一个一维数组 
 System.out.println("一维数组中的元素分别为:");//输出信息
 for(int x:arr){
  //foreach语句,int x引用变量,arr指定要循环遍历的数组,最后将X输出
  System.out.println(x);
 }
}
}

执行结果为:2-100之间的所有偶数之和为2550

猜你喜欢

转载自www.cnblogs.com/wzhdcyy/p/9252300.html