简体   繁体   中英

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.

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 .

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

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

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

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.

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 i<100 || j>34 .

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, "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM