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

标签 java loops for-loop while-loop

我需要修改程序,以便对于所有大于或等于 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/

相关文章:

java - 多线程处理日志文件,如何保持日志文件中的行顺序

c - 前缀和的并行化 (Openmp)

r - For循环提取数据

java - 自然语言处理——将非结构化书目转换为结构化元数据

java - jframe 中的 UnsupportedOperationException : Not supported yet.

javascript - 如何过滤属于数组值一部分的对象?

swift - Alamofire 调用在循环内不起作用

javascript - 嵌套for循环,每个循环单独延迟

for循环内的计数器没有给出预期的输出

java - 将其存储在mapdb中的最佳方法?