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