我理解一个根据情况比另一个具有某些优势的概念,但是它们在每种情况下都可以互换吗?我的教科书写道
for (init; test; step) {
statements;
}
等同于
init;
while (test) {
statements;
step;
}
我将如何在 for 循环中重写以下程序?如果我将以下程序重新编写为 for 循环表单,我将无法设置 init 和测试的值。
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
int n = readInt("enter a positive number: ");
int dsum = 0;
while ( n > 0) {
dsum += n % 10;
n /=10;
}
}
}