gpt4 book ai didi

java - 我如何使用 For 循环而不是 while 来做同样的事情?

转载 作者:行者123 更新时间:2023-11-30 03:15:23 25 4
gpt4 key购买 nike

我需要修改程序,以便对于所有大于或等于 0 的 k 值,程序像以前一样工作,但对于所有小于 0 的 k 值,程序显示,k, k -1, k-2, … 0。只能使用 for 循环。 所以我的代码是这样的,使用 while 循环,

     while (i != k && k > 0) {
i = i + 1;
System.out.println(i);
}
while (k <= 0) {
System.out.println(k);
k = k + 1;
}

我成功地处理了正数,但我在处理负数时遇到了问题。

这是我为积极的一面而写的 for 循环

    for (int i = 0; i <= k; i = i + 1) {
System.out.println(i);
}

请帮忙!!!

最佳答案

The for Statement 的 Oracle 文档说(部分)

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

 for (initialization; termination; increment) {
statement(s)
}

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

tl;dr你可以做类似的事情

for (; i != k && k > 0;) {
System.out.println(++i);
}
for (; k <= 0; k++) {
System.out.println(k);
}

关于java - 我如何使用 For 循环而不是 while 来做同样的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32774666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com