java - 类似的 while 循环和 do while 循环之间的输出差异?

标签 java loops while-loop compare do-while

对于我的 Java 类,我被要求创建一个 while 循环,然后将其转换为 do-while 循环,然后比较输出。这是问题:

  1. Replace the while loop in question 4 with a do while loop. What is the possible difference between the output from question 4 and this question?

无论可能与否,我都找不到输出的差异。这是下面两者的代码和输出。

while循环

package fordemo;
import java.util.Scanner;

public class ForDemo {


public static void main(String[] args) {

    System.out.println("Input a number:");
    Scanner user_input = new Scanner (System.in);
    int number = user_input.nextInt();
    int n = -1;
    while (n < number){
        n=n+2;
        System.out.print(n + " ");

    }
  }
}

运行:

Input a number:
15
1 3 5 7 9 11 13 15 BUILD SUCCESSFUL (total time: 1 second)

do-while 循环

package fordemo;
import java.util.Scanner;

public class ForDemo {


public static void main(String[] args) {

    Scanner user_input = new Scanner (System.in);
    System.out.println("Input a number:");
    int number = user_input.nextInt();
    int n = -1; 
    do {
        n+=2;
        System.out.print(n + " ");
    }
    while (n < number);            

  }
}

运行:

Input a number:
11
1 3 5 7 9 11 BUILD SUCCESSFUL (total time: 1 second)

最佳答案

while (condition) {something}do {something} while (condition) 之间的区别在于后者总是至少执行一次。/em>

前者在迭代之前检查条件,后者在迭代之后检查条件。

如果您输入 -1 或更少,前者不会给您任何结果,而后者将为您提供 1

以最简单的形式,您可以查看两行之间的差异:

while (false) { System.out.println("x"); }
do { System.out.println("x"); } while (false);

前者强烈提示无法访问的代码,因为它永远不会进入循环。后者不会提示,因为它运行一次循环。

关于java - 类似的 while 循环和 do while 循环之间的输出差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25861618/

相关文章:

javascript - 如何同时使用 if 和 while Javascript 设置 3 个条件

java - 如何将用户输入的数字(学生 ID)拆分为公式

java - JDICplus在Java中嵌入IE的问题

java - Hibernate 将父级与分离的子级合并

php - 帮助递归函数从一个数据库查询创建父/子树

python - 使用!=获得python while语句

java - Netflix Zuul 服务器-/路由端点不可用

java - BigDecimal:Java 编译器可以优化乘以 1 的乘法吗?

javascript - 如何循环根据 div 中每个字母的位置修改文本的替换函数?

java - 固定时间后中止循环