while与do-while循环的使用

/*
 1.格式:
       ①初始化条件
       while(②循环条件){
           ④循环体
           ③迭代条件
       }
 2.for循环与while可以相互转换的 。     
 */
public class TestWhile {
//100以内的偶数的输出,及其和
public static void main(String[] args) { int i = 1; int sum = 0; while (i <= 100) { if (i % 2 == 0) { System.out.println(i); sum += i; } i++; } System.out.println(sum); } }

 

do--while():

/*
1. 格式:  
          ①初始化条件
          do{
           ④循环体
           ③迭代条件
    }while(②循环条件)
 */
public class TestDoWhile {
    public static void main(String[] args) {
        int i = 1;
        do{
        if(i %2 ==0){
               System.out.println(i);    
             }
            i++;
        }while(i<=100);
    }
}

 

区别:do-while至少会经过一次。

 

 

练习1 :  输入个数不确定的整数,判断输入的正数和负数的个数, 当输入为0 时结束程序

import java.util.Scanner;
public class TestEnter {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int a = 0;// 正数的个数
        int b = 0;// 负数的个数
        for (;;) {
            System.out.println("输入整数:");
            int num = s.nextInt();
            if (num > 0) {
                a++;
            } else if (num < 0) {
                b++;
            } else
                break;
        }
        System.out.println("正数:" + a + "负数:" + b);
    }
}

 

无限循环:

for( ; ; ){

}

或者while(true){

}

说明:一般情况下, 在无限循环内部都要有程序终止的语句,使用 break 实现,若没有,那就是死循环!

 

posted @ 2020-03-08 16:16  林淼零  阅读(614)  评论(0编辑  收藏  举报