如何将此for循环转换为while循环?

bla*_*ops 1 java arrays for-loop while-loop

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

如果我有for循环:

int [] list = new int [5];

for (int i = 0; i < 5; i++) {
    list [i] = i + 2;
}
Run Code Online (Sandbox Code Playgroud)

我怎么能把它变成一个while循环?

这是我的尝试

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

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

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

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

这是第21行

System.out.print(list[i] + " ");
Run Code Online (Sandbox Code Playgroud)

And*_*ner 9

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

for ( ForInit ; Expression ; ForUpdate ) Statement
Run Code Online (Sandbox Code Playgroud)
  • ForInit是初始化器.它首先运行以设置变量等.
  • Expression是一个布尔条件来检查是否Statement应该运行
  • Statement是如果Expression为true则要运行的代码块
  • ForUpdateStatement如果需要,在例如更新变量之后运行

ForUpdate运行完毕后,Expression再次进行评估.如果它仍然是真的,Statement则再次执行,然后ForUpdate; 重复这个直到Expression是假的.

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

ForInit;
while (Expression) {
  Statement;
  ForUpdate;
}
Run Code Online (Sandbox Code Playgroud)

为了将此模式应用于"真实"for循环,只需替换上面描述的块.

对于上面的例子:

  • 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++;
}
Run Code Online (Sandbox Code Playgroud)