hn_tired
hn_tired

Reputation: 942

How to use two conditions (greater than and less than) for termination of a for loop in Java?

I was wondering, do you have a neat way of doing this ?

for (int i = 0; 4 > i < banners.size() ; i++) {
    doSomeThing
}

bannrs.size maybe between 0 to 10 but i want just 4 time or less do work

Upvotes: 0

Views: 222

Answers (3)

Sribalaji
Sribalaji

Reputation: 11

You should probably start your loop with 4 because all the other conditions less than 4 are not going to fulfill your requirement and waste of iteration. So the loop goes for(int i=4;i

}

Upvotes: 0

f1sh
f1sh

Reputation: 11941

Combine the conditions like this:

for (int i = 0; 4 > i && i < banners.size() ; i++) {
}

But this loop will terminate right away, so you probably want something like this:

for (int i = 0; i < banners.size() ; i++) {
  if(4 > i){
    continue;
  }
}

Upvotes: 1

Eran
Eran

Reputation: 393986

Yes:

for (int i = 0; i < Math.min(4,banners.size()) ; i++) {

}

BTW, based on your question's title, perhaps you intended to have i in the range 4 < i < banners.size(). If that's the case, you can simply initialize i to 5:

for (int i = 5; i < banners.size() ; i++) {

}

Upvotes: 5

Related Questions