James
James

Reputation: 11

Java Changing For to While

I would like to change this for loop to a while statement:

for (int x = 0; x < items.size(); x++) {...}

I've tried:

int x = 0;
while(x<items.size()){
x++;
...
}

but it won't work.

Upvotes: 1

Views: 7945

Answers (3)

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

Your code should have been as follows,

int x = 0;
while(x<items.size()){
...
...
...
x++;
}  

The reason for x++ operation to be the last statement in the loop is to increment the value of 'x' only when we are done with the loop and we need to increment the value of looping variable.

If you put x++ in the starting of looping code, the code will not work for the last looping scheme, wherein, prior to entering the loop, the value of x would have been x=items.Size( );. So it wouldn't be able to enter the loop as the condition is x<items.Size();

Upvotes: 2

Nav
Nav

Reputation: 20658

It should be

int x = 0;
while(x<items.size()){
...

x++;
}

With the x++ in the end of the loop (because in the for loop, the increment section is executed only after the program control reaches the closing braces), but otherwise everything looks ok. It should work.

Upvotes: 5

Mauricio
Mauricio

Reputation: 5853

put the x++ at the end of the while block.

while(x<items.size()){
...
x++;
}

Upvotes: 7

Related Questions