zoukankan      html  css  js  c++  java
  • 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 实现,若没有,那就是死循环!

    All that work will definitely pay off
  • 相关阅读:
    xml模塊
    xlrd,xlwt模塊
    logging模塊
    正則補充
    Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面
    安卓--子线程和主线程之间的交互实例(时钟)
    Android--全局获取Context的技巧
    Android 广播机制
    android编写Service入门
    Android的Looper,Handler以及线程间的通信
  • 原文地址:https://www.cnblogs.com/afangfang/p/12443062.html
Copyright © 2011-2022 走看看