AndreiBogdan
AndreiBogdan

Reputation: 11164

Java. Why doesn't this for loop work correctly

I have the next for loop header:

for ( int row = interval[intRow][_START_]; row <= interval[intRow][_END_]; row++ )

where interval is of type/dimension int[15][5], intRow is of value 1 and _START_ and _END_ are constants, start being 0 and end being 1;

interval[intRow][_START_] returns 1 and interval[intRow][_END_] returns 2

Why the hell does row only go till 1 (so just one loop instead of 2)?

I've noticed that if i put the second condition, or whatever it's called, in between two ( ... ) then it works, it does the loop twice. What i mean is:

for ( int row = interval[intRow][_START_]; row <= (interval[intRow][_END_]); row++ )

Has anyone got any ideas on why this is happening? I know i can just put them between two parenthesis, but i'd like to know why this doesn't work.

Thanks.

EDIT1

It's <= not < ... I made a typo at the beginning. Sorry.

EDIT2

Basically this would look like:

for ( int row = interval[1][0]; row <= interval[1][1]; row++ )

where interval[1][0] == 1 and interval[1][1] == 2

Upvotes: 1

Views: 579

Answers (3)

sgp15
sgp15

Reputation: 1280

Tried following.

int[][] interval = new int [15][5];

int intRow = 1;
int _START_ = 0;
int _END_ = 1;

interval[intRow][_START_] = 1;
interval[intRow][_END_] = 2;

for ( int row = interval[intRow][_START_]; row <= interval[intRow][_END_]; row++ ) {

    System.out.println(row);
}

Output: 1 2

TO summarize, its working fine for me. Which makes me wonder if interval[intRow][_END_] is being set correctly.

Try using debugger or simply Sysouts to debug your program.

Upvotes: 1

Joand
Joand

Reputation: 342

Did you try to write this ?

for ( int row = interval[intRow][_START_]; row <= interval[intRow][_END_]; row++ )

or this ?

for ( int row = interval[intRow][_START_]; row < interval[intRow][_END_] +1; row++ )

Upvotes: 0

Thomas
Thomas

Reputation: 5094

Loop1 : 1<2 - OK Loop2 : 2<2 - not ok

Try <=

Upvotes: 3

Related Questions