zoukankan      html  css  js  c++  java
  • for while do while 循环的注意事项和练习

    2020-04-12三种循环的写法

        public static void main(String[] args) {
            //fou 循环    当循环次数固定时 ,建议使用for循环
            for (;;){
                //循环体
            }
            //当循环次数不固定时 ,建议使用while循环、do while 循环
            //while 循环  先判断 再循环   先判断,再执行,则使用while循环。
            while(条件){
                //循环体
            }
            //do while 循环  先循环在判断  先执行,然后再判断,则使用do while 循环。
            do{
                //循环体
            }while(条件)
    
        }

    for循环的注意事项

     1  public static void main(String[] args) {
     2         //注意: 1.在for循环中,三个 表达式都可以省略,但是分号必须编写,则出现死循环也叫做无限循坏,解决办法:按
     3         /*     for(;;){
     4                 System . out . println ("OK") ;
     5         }*/
     6         //注意: 2.在for循环中,省略表达式1,则出现编译错误,解决办法:将表达式1编写在for循环上面
     7             /*      int i = 1;
     8                     for(;i <= 5;i++) {
     9                          System. out .println(i) ;
    10                     }
    11              */
    12         //注意: 3.在for循环中,省略表达式2,则出现死循环或无限循环,也就是说当省略表达式2时,则条件默认为true
    13             /*  for(int i = 1; ;i++) {
    14                      System. out.println(i) ;
    15             }*/
    16         //注意: 4. 在for循环中,当省略表达式3,则出现死循环,解决办法:将表达式3编写在循环体中最后一条语句
    17             /*    for(int i = 1;i <= 5;){
    18                     System . out. println (i) ;
    19                    i++;
    20             }*/

    while 循环练习题 

    使用while循环完成输出所有三位数中能被4整除的数,并且每行显示5个
     1 public static void main(String[] args) {
     2         //练习10:使用while循环完成输出所有三位数中能被4整除的数,并且每行显示5个
     3         int i = 100;
     4         int count = 0;//用来计算有几个能被4整除的数字
     5         while (i<=999){
     6             if(i%4 == 0){
     7                 System.out.print(i+"	");
     8                 count++;
     9                 if(count%5 == 0){
    10                     System.out.println();
    11                 }
    12 
    13             }
    14             i++;
    15     }
    17      System.out.println(count);
    18   }

    循环不同点

    ➢执行顺序不同。
    ■for 循环和while循环:先判断当条件为true时,然后再执行。
    ■do while循环:先执行循环体,然后再判断条件。
    ➢使用情况不同。
    ■当循环次数固定时 ,建议使用for循环
    ■当循环次数不固定时 ,建议使用while循环、do while 循环
    ◆先判断,再执行,则使用while循环。
    ◆先执行,然后再判断,则使用do while 循环。

  • 相关阅读:
    Spring基础知识
    Hibernate基础知识
    Struts2基础知识
    在eclipse里头用checkstyle检查项目出现 File contains tab characters (this is the first instance)原因
    java后台获取cookie里面值得方法
    ckplayer 中的style.swf 中的 style.xml 中的修改方法
    java hql case when 的用法
    Windows下Mongodb安装及配置
    Mongodb中经常出现的错误(汇总)child process failed, exited with error number
    Mac 安装mongodb
  • 原文地址:https://www.cnblogs.com/dupeilin/p/12678214.html
Copyright © 2011-2022 走看看