【发布时间】:2014-09-16 06:01:02
【问题描述】:
对于我的 Java 类,我被要求创建一个 while 循环,然后将其转换为一个 do-while 循环,然后比较输出。这是问题:
- 将问题 4 中的 while 循环替换为 do while 循环。问题 4 的输出与本问题可能有什么区别?
我找不到输出的差异,可能与否。这是下面两者的代码和输出。
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)
执行循环
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)
【问题讨论】:
-
为什么不输入一个小于
-1的数字并检查会发生什么? -
输入小于-1然后你就会看到差异
-
do-while 循环
run: Input a number: -9 1 BUILD SUCCESSFUL (total time: 2 seconds) -
@IAmTheWalrus:然后对
while循环执行相同操作,您就有了答案。 Paxdiablo 告诉你原因。 -
while 循环
Input a number: -11 BUILD SUCCESSFUL (total time: 2 seconds)
标签: java loops while-loop compare do-while