问题
I am creating an array program. I am practicing how to convert for loops to while 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] + " ");
回答1:
The general structure of a basic for statement is:
for ( ForInit ; Expression ; ForUpdate ) Statement
ForInitis the initializer. It is run first to set up variables etc.Expressionis a boolean condition to check to see ifStatementshould be runStatementis the block of code to be run ifExpressionis trueForUpdateis run after theStatementto 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 = 0Expression=>i < 5ForUpdate=>i++Statement=>list [i] = i + 2;
Putting it together:
int i = 0;
while (i < 5) {
list[i] = i + 2;
i++;
}
回答2:
int [] list = new int [5];
int i = 0; // initialization
while (i < 5) { // condition
list [i] = i + 2;
i++; // afterthought
}
The for loop posted is pretty much a shorthand for the above. The first part of a for loop is called the initialization, equivalent to the int i = 0; in the above code. The next is called the condition, which, if true, will cause the loop to be run again; this is the i < 5 part. Finally there is the afterthought, which changes the iterator i (usually an increment of one for iterating over an array). The for loop simply condenses these three parts into one line, as such:
for (initialization; condition; afterthought) {
}
回答3:
Your while loop is perfetly fine, but after it ends, the value of i is 5. Since java arrays are always indexed from zero, list[5] doesn't exist and accessing it throws exception.
That's what you see when printing System.out.print(list[i] + " "); Just print any other element, list[1], list[4] or list[0] for example.
来源:https://stackoverflow.com/questions/36023297/how-do-i-convert-this-for-loop-into-a-while-loop