我如何将这个for循环转换为while循环? [英] How do I convert this for loop into a while loop?
问题描述
我正在创建一个数组程序。我正在练习如何将循环转换为
循环,但是我无法理解这个概念。
如果我有 for
循环:
int [] list = new int [5];
for(int i = 0; i <5; i ++){
list [i] = i + 2;
$ / code>
我如何使它成为而
循环?
这是我的尝试
$ b $ pre $ int [ ] list = new int [5];
int i = 0;
while(i <5){
list [i] = i + 2;
i ++;
}
System.out.print(list [i] +);
这是我认为应该完成的事情,但在我的电脑中出现错误。 / p>
线程main中的异常java.lang.ArrayIndexOutOfBoundsException:5在Arrays2.main(Arrays2.java:21)
这是行21
System.out。 print(list [i] +);
一个基本的for语句的一般结构是:< (ForInit; Expression; ForUpdate)语句
。如果它仍然是真的,再次执行
ForInit
是初始值设定项。它是首先设置变量等。
表达式
是一个布尔条件来检查是否Statement
应该运行
语句
是要运行的代码块,如果Expression
为true
ForUpdate
在Statement
例如根据需要更新变量
在
ForUpdate
再次评估c>表达式Statement
,那么ForUpdate
;直到表达式
为假。
您可以按如下方式将其重构为一个while循环:
ForInit;
while(Expression){
Statement;
ForUpdate;
$ b $为了将这个模式应用到一个真正的for循环,只需要替换如上所述。
以上例子:
ForInit
=>int i = 0
/ code> =>
i < 5
ForUpdate
=>i ++
语句
=>list [i] = i + 2;
我= 0;
while(i <5){
list [i] = i + 2;
i ++;
}
I am creating an array program. I am practicing how to convert
for
loops towhile
loops, but I cannot grasp the concept.If I have the
for
loop:int [] list = new int [5]; for (int i = 0; i < 5; i++) { list [i] = i + 2; }
How would I make it a
while
loop?Here's my attempt
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.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Arrays2.main(Arrays2.java:21)
This is line 21
System.out.print(list[i] + " ");
解决方案The general structure of a basic for statement is:
for ( ForInit ; Expression ; ForUpdate ) Statement
ForInit
is the initializer. It is run first to set up variables etc.Expression
is a boolean condition to check to see ifStatement
should be runStatement
is the block of code to be run ifExpression
is trueForUpdate
is run after theStatement
to e.g. update variables as necessary
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.
You can restructure this as a while loop as follows:
ForInit;
while (Expression) {
Statement;
ForUpdate;
}
In order to apply this pattern to a "real" for loop, just substitute your blocks as described above.
For your example above:
ForInit
=>int i = 0
Expression
=>i < 5
ForUpdate
=>i++
Statement
=>list [i] = i + 2;
Putting it together:
int i = 0;
while (i < 5) {
list[i] = i + 2;
i++;
}
这篇关于我如何将这个for循环转换为while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!