如何将此 for 循环转换为 while 循环? [英] How do I convert this for loop into a while loop?

查看:29
本文介绍了如何将此 for 循环转换为 while 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个数组程序.我正在练习如何将 for 循环转换为 while 循环,但我无法理解这个概念.

I am creating an array program. I am practicing how to convert for loops to while loops, but I cannot grasp the concept.

如果我有 for 循环:

int [] list = new int [5];

for (int i = 0; i < 5; i++) {
    list [i] = i + 2;
}

如何使它成为 while 循环?

How would I make it a while loop?

这是我的尝试

int [] list = new int [5];
int i = 0;

while (i<5) {
    list [i] = i + 2;
    i++;
}
System.out.print(list[i] + " ");

这是我认为应该做的,但它在我的计算机中出现错误.

This is what I think should be done, but it comes up as an error in my computer.

线程main"中的异常 java.lang.ArrayIndexOutOfBoundsException: 5 at Arrays2.main(Arrays2.java:21)

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Arrays2.main(Arrays2.java:21)

这是第 21 行

System.out.print(list[i] + " ");

推荐答案

基本for语句的一般结构是:

The general structure of a basic for statement is:

for ( ForInit ; Expression ; ForUpdate ) Statement

  • ForInit 是初始值设定项.它首先运行以设置变量等.
  • Expression 是一个布尔条件,用于检查是否应该运行 Statement
  • StatementExpression 为真时要运行的代码块
  • ForUpdateStatement 之后运行,例如根据需要更新变量
    • ForInit is the initializer. It is run first to set up variables etc.
    • Expression is a boolean condition to check to see if Statement should be run
    • Statement is the block of code to be run if Expression is true
    • ForUpdate is run after the Statement to e.g. update variables as necessary
    • ForUpdate 运行后,再次评估 Expression.如果仍然为真,则再次执行Statement,然后ForUpdate;重复此操作,直到 Expression 为 false.

      After ForUpdate has been run, Expression is evaluated again. If it is still true, Statement is executed again, then ForUpdate; repeat this until Expression is false.

      您可以将其重构为 while 循环,如下所示:

      You can restructure this as a while loop as follows:

      ForInit;
      while (Expression) {
        Statement;
        ForUpdate;
      }
      

      为了将此模式应用于真正的"for 循环,只需按照上述方法替换您的块.

      In order to apply this pattern to a "real" for loop, just substitute your blocks as described above.

      对于上面的示例:

      • ForInit => int i = 0
      • 表达式 => i <5
      • ForUpdate => i++
      • 语句 => list [i] = i + 2;
      • ForInit => int i = 0
      • Expression => i < 5
      • ForUpdate => i++
      • Statement => list [i] = i + 2;

      组合起来:

      int i = 0;
      while (i < 5) {
        list[i] = i + 2;
        i++;
      }
      

      这篇关于如何将此 for 循环转换为 while 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆