unmultimedio
unmultimedio

Reputation: 1244

Is it possible to declare several 'for' loop terminations in Java?

I know the sintax in the for loop in Java. Normally looks something like

for(initialization; termination; increment){
    ...
}
//Example
for(int i=0; i<100; i++){
    ...
}

And I also know already that we can declare several initializations and increments, such as

//Example
int i,j;
//  ini1,  ini2 ;  term ;  inc1,  inc2
for(i=0,   j=100;  i<100;  i++,   j--){
    ...
}

My very clear question is: Is it possible to have more than one termination as well? something may be like

//Example
int i,j;
//  ini1,   ini2 ;   term1,   term2;   inc1,  inc2
for(i=0,    j=100;   i<100,   j>34;    i++,   j--){
    ...
}

Because I'm trying it and it's giving me an error, and I'd rather not to use too many if sentences inside the loop to determine wether to continue or break.

Is it sintax, or it's just not pssible? Thanks in advance.

Upvotes: 2

Views: 74

Answers (6)

mawia
mawia

Reputation: 9349

you can give as many conditions,combined by Logical AND/OR,as you wish given that your expression evaluate to a boolean true/false value.

As per Java Language specification,Java SE 7 Edition:

"The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

BasicForStatement: for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement"

...The Expression must have type boolean or Boolean,"

Upvotes: 1

Pshemo
Pshemo

Reputation: 124275

There can be only one... condition in for loop, but this condition can be build from few others, using logical operators like && which means "AND", || which means "OR"?

If you want to end loop if all conditions i<100, j>34 are fulfilled then you should use logical AND operator i<100 && j>34.
If you want to end loop if at least one of conditions i<100, j>34 is fulfilled then you should use logical OR operator i<100 || j>34.

Upvotes: 1

eKek0
eKek0

Reputation: 23309

You are trying to stop when i<100 AND j>34. In java, an AND is writen with &&. So, your loop can be:

int i,j;
for(i=0,    j=100;   i<100 &&   j>34;    i++,   j--){
    ...
}

Read, at least, this for more information.

Upvotes: 1

Just use the logical operators || and && to indicate your stopping conditions:

for(i=0, j=100; i < 100 || j > 34; i++, j--)

Upvotes: 1

//Example
int i,j;
//  ini1,   ini2 ;   term1,   term2;   inc1,  inc2
for(i=0,    j=100;   i<100 &&  j>34;    i++,   j--){
    ...
}

Upvotes: 1

rgettman
rgettman

Reputation: 178303

You can supply any boolean condition, which may include logical boolean operators such as !, &&, and/or ||:

for(i=0,    j=100;  i<100 && j>34;    i++,   j--){

They can be as simple or complex as you'd like, as long as it evaluates to a boolean.

Upvotes: 2

Related Questions