JavaSE 第七讲 Flow Control Statement Cont. 9.26

1.While 循环

public class WhileTest
{
   public static void main(String[] args)
   {
           int a = 1;//循环变量
       int sum = 0;//存储相加后的结果

       while(a <= 100)
       {
            sum += a;
        a++;
       } 

       System.out.println(sum);
   }
}

2.do...while 循环

public class DoWhileTest
{
    public static void main(String[] args)
{
       /*  
       int a = 1;
       int sum = 0;

       do
       {
          sum += a;
      a++;
       }
       while(a <= 100);

       System.out.println(sum);
       */

    int a = 2;
    int sum = 0;//存储相加后的结果

    do
    {
        sum += a;
        a += 2;
    }
    while(a <= 100);
    System.out.println(sum);

    int b = 2;

    while(b < 1)
    {
           System.out.println("Hello World");
    }

    do
    {
           System.out.print("Welcome");
    }
    while(b < 1);
}
}

3.for 循环

public class ForTest
{
     public static void main(String[] args)
 {
         int sum = 0;
     for(int i = 1; i <= 100; i++)
     {
             sum += i;
     }
     System.out.println(sum);


     int sum2 = 0;
     for(int i = 100;i >= 1; i -= 2)
     {
          sum2 += i;
     }
     System.out.println(sum2);
 }
}

你可能感兴趣的:(JavaSE 第七讲 Flow Control Statement Cont. 9.26)