【问题标题】:When would a do-while loop be the better than a while-loop?do-while 循环何时会比 while-loop 更好?
【发布时间】:2013-12-26 15:41:10
【问题描述】:

这是一个非常主观的问题,所以我会更具体。是否有任何时候 do-while 循环比普通的 while 循环更好?

例如

int count = 0;
do {
   System.out.println("Welcome to Java");
   count++;
} while (count < 10);`

在评估 do 语句后检查 while 条件对我来说似乎没有意义(也就是强制 do 语句至少运行一次)。

对于像我上面的例子这样简单的事情,我会想象:

int count = 0; 
while(count < 10) { 
   System.out.println("Welcome to Java"); count++;
}

通常会被认为是用更好的写作风格编写的。

谁能提供一个可行的示例,说明何时将 do-while 循环视为唯一/最佳选择?你的代码中有一个 do-while 循环吗?它扮演什么角色?为什么选择 do-while 循环?

(我有一种预感,do-while 循环可能在编码游戏中有用。请纠正我,游戏开发者,如果我错了!)

【问题讨论】:

标签: java loops while-loop do-while


【解决方案1】:

如果你想从网络套接字读取数据直到找到一个字符序列,你首先需要读取数据,然后检查数据是否有转义序列。

do
{ 
   // read data
} while ( /* data is not escape sequence */ );

【讨论】:

    【解决方案2】:

    while 语句在特定条件为真时持续执行语句块

    while (expression) {
         statement(s)
    }
    

    do-while 在循环底部计算其表达式,因此,do 块中的语句总是至少执行一次。

    do {
         statement(s)
    } while (expression);
    

    现在来说说功能上的区别,

    while-loops 由条件分支指令(例如 if_icmpge 或 if_icmplt)和 goto 语句组成。条件指令将执行分支到循环之后立即执行的指令,因此如果条件不满足,则终止循环。循环中的最后一条指令是一个 goto,它将字节码分支回循环的开头,确保字节码继续循环,直到满足条件分支。

    A Do-while-loops 也与 for 循环和 while 循环非常相似,只是它们不需要 goto 指令,因为条件分支是最后一条指令,用于循环回到开头 do-while 循环总是至少运行一次循环体——它会跳过初始条件检查。由于它跳过了第一次检查,因此将少一个分支和一个要评估的条件。

    通过使用do-while,如果表达式/条件很复杂,您可能会获得性能,因为它可以确保至少循环一次。那样的话do-while could call for performance gain

    这里的发现非常令人印象深刻, http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html#while_loop

    【讨论】:

      【解决方案3】:

      do-while 循环基本上是 while 循环的反转版本。

      它第一次无条件地执行循环语句。

      然后在再次执行语句之前计算指定的条件表达式。

      int sum = 0;
      int i = 0;
      do
      {
          sum += ids[i];
          i++;
      } while (i < 4);
      

      Reference material

      【讨论】:

        【解决方案4】:

        简单地说,当你想先检查条件然后执行操作while是更好的选择,如果你想执行操作至少一次然后检查条件do-while更好.
        根据您的问题,一个可行的示例,
        1。当我需要找到可以在同一类或超类或该超类的超类中声明的field 时,以此类推,即找到位于深层类层次结构中的字段。 (A extends BB extends C等等)

        public Field SearchFieldInHierarchy(Object classObj, String fieldName )
        {
            Field type = null;
            Class clz = classObj.getClass();
            do
            {
                try
                {
                    type = clz.getDeclaredField(fieldName);
                    break;
                } catch (NoSuchFieldException e)
                {
                    clz = clz.getSuperclass();
                } 
            } while(clz != null || clz != Object.class);        
            return type;
        }
        

        2。从Http响应读取输入流时

            do 
            {
                bytesRead = inputStream.read(buffer, totalBytesRead, buffer.length - totalBytesRead);
                totalBytesRead += bytesRead;
            } while (totalBytesRead < buffer.length && bytesRead != 0);
        

        【讨论】:

          【解决方案5】:

          你自己来回答这个问题——当它需要运行至少一次时,这样理解是有意义的。

          【讨论】:

            【解决方案6】:

            do - while 循环允许您确保代码在进入迭代之前至少执行一次。

            【讨论】:

              【解决方案7】:

              while 循环中,条件在执行循环中的代码之前进行测试。在do while 循环中,代码在条件测试之前执行,导致代码始终至少执行一次。示例:

              $value = 5;
              
              while($value > 10){
                  echo "Value is greater than 10";
              }
              

              上面永远不会输出任何东西。如果我们再次这样做:

              $value = 5;
              
              do{
                  echo "Value is greater than 10";
              }while($value > 10)
              

              它会输出Value is greater than 10,因为条件是在循环执行后测试的。在此之后,它不会进一步输出任何内容。

              【讨论】:

                【解决方案8】:

                do-while 和 while 的区别在于 do-while 在循环底部而不是顶部计算其表达式。因此,do 块中的语句总是至少执行一次。

                例如,请检查此链接:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

                【讨论】:

                  【解决方案9】:

                  如果只有在循环的第一步之后才能知道循环条件(当您在进入循环之前不想要条件时)。 通常:

                  do {
                    expr = ...;
                  while (expr);
                  

                  【讨论】:

                  【解决方案10】:

                  当你必须重复检查一个条件时使用while语句,只有当条件满足时才执行循环

                  while(condition) //eg. a>5
                  {
                  Body of Loop
                  }
                  
                  • 如果您在此处查看控制流程,您可以看到在执行循环之前检查条件,如果条件不满足,则根本不会执行循环

                  在 Do-While 语句中,程序将执行一次循环体,然后检查语句是否为真

                  do
                      {
                  Body of Loop
                  }
                  
                  while(condition); //eg. a>5
                  
                  • 如果您注意到这里的控制流程,您将看到主体执行一次,然后检查条件。如果条件为 False 则程序将跳出循环,如果为 True 则继续执行直到条件不满足为止
                  • 需要注意的是,while 和 do-while 给出相同的输出,只是控制流不同

                  【讨论】:

                    【解决方案11】:

                    /* while循环

                    5 美元

                    1 块巧克力 = 1 美元

                    while my money is greater than 1 bucks 
                      select chocolate
                      pay 1 bucks to the shopkeeper
                      money = money - 1
                    end
                    

                    回家后不能去购物,因为我的钱 = 0 美元 */

                    #include<stdio.h>
                    int main(){
                      int money = 5;
                    
                      while( money >= 1){   
                        printf("inside the shopk and selecting chocolate\n");
                        printf("after selecting chocolate paying 1 bucks\n");
                        money = money - 1 ;  
                        printf("my remaining moeny = %d\n", money);
                        printf("\n\n");
                      }
                    
                      printf("dont have money cant go inside the shop, money = %d",  money);
                    
                      return 0;
                    } 
                    

                    无限金钱

                    while( codition ){ // condition will always true ....infinite loop
                      statement(s)
                    }
                    

                    请观看此视频以更好地理解 https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s

                    【讨论】:

                      【解决方案12】:

                      区分两者非常简单。我们先来看看 While 循环。

                      while循环的语法如下:

                      // expression value is available, and its value "matter".
                      // if true, while block will never be executed.
                      while(expression) {
                          // When inside while block, statements are executed, and
                          // expression is again evaluated to check the condition. 
                          // If the condition is true, the while block is again iterated
                          // else it exists the while block.
                      }
                      

                      现在,让我们来看看 do-while 循环。 do-while 的语法不同:

                      // expression value is available but "doesn't matter" before this loop, & the 
                      // control starts executing the while block.
                      do {
                         // statements are executed, and the
                         // statements is evaluated and to check the condition. If true 
                         // the while block is iterated, else it exits. 
                      } while(expression);
                      

                      下面给出了一个示例程序来说明这个概念:

                      public class WhileAndDoWhile {
                      
                        public static void main(String args[]) {
                          int i = 10;
                          System.out.println("While");
                          while (i >= 1) {
                              System.out.println(i);
                              i--;
                          }
                          // Here i is already 0, not >= 1.
                          System.out.println("do-while");
                          do {
                              System.out.println(i);
                              i--;
                          } while (i >= 1);
                        }
                      }
                      

                      编译运行这个程序,区别就很明显了。

                      【讨论】:

                        猜你喜欢
                        • 2011-12-16
                        • 2015-12-20
                        • 2020-08-28
                        • 2016-02-21
                        • 1970-01-01
                        • 2013-06-28
                        • 2021-02-01
                        • 2015-02-16
                        相关资源
                        最近更新 更多