AncientSwordRage
AncientSwordRage

Reputation: 7645

Why is my for loop telling me Syntax error, insert "AssignmentOperator Expression"?

I have some code, like so:

int batchPosition = new Integer(batchBegin);

for (batchPosition;batchPosition<=batchEnd;batchPosition++)

But I get this error in eclipse:

Syntax error, insert "AssignmentOperator Expression" to complete ForInit.

I've looked at various posts on SO about this error, and googled it but I can't figure out why this isn't allowed.

Upvotes: 0

Views: 2855

Answers (3)

Azodious
Azodious

Reputation: 13882

for loop contains 4 parts of execution:

initialization, Condition, execution-body, increment or decrement

int batchPosition = new Integer(batchBegin);  

for (batchPostion;batchPosition<=batchEnd;batchPosition++) 

You've missed the initialization part.

Either ignore it at all cause before for you've already initialized

for (;batchPosition<=batchEnd;batchPosition++) 

OR

Move the line before for to inside for

for (int batchPosition = new Integer(batchBegin);batchPosition<=batchEnd;batchPosition++) 

but, in latter case, you won't be able to use batchPosition outside for scope.

Upvotes: 1

assylias
assylias

Reputation: 328835

batchPosition on it's own is not a valid initialisation statement - you can simply skip it:

int batchPosition = new Integer(batchBegin);

for (; batchPosition <= batchEnd; batchPosition++)

But if you don't need to access batchPosition after your loop, it is good practice to reduce variables scopes as much as possible:

for (int batchPosition = new Integer(batchBegin); batchPosition <= batchEnd; batchPosition++)

Upvotes: 5

AncientSwordRage
AncientSwordRage

Reputation: 7645

For some reason Java or Eclipse (or bother) doesn't like this part of the loop:

for (batchPostion....

It expects the variable being used to count position (batchPosition) in the loop to be initialised in the loop header (the for(first;only when;repeat) part.) I would guess this is because wants it to only be local to the loop.

To fix just move you assignment into the header, like so:

for (int batchPosition = new Integer (batchBegin);batchPosition<=batchEnd;batchPosition++)

Not as pretty, but it will work.

Upvotes: 1

Related Questions