Reputation: 200
for (int i=0; i < string.length() || i < 5 ; i++) {
// some code
}
Is it possible to evaluate the middle part based on whichever expression is smaller?
Upvotes: 1
Views: 162
Reputation: 521409
You can phrase your loop as this:
for (int i=0; i < Math.min(string.length(), 5); i++) {
// some code
}
Here we are taking the smaller of 5 or the string length as the upper bound of the loop, and the code is clear to someone else who might have to read it.
Upvotes: 3
Reputation: 393851
If you want the loop to terminate when i
reaches the smaller of the two expressions, use AND:
for(int i=0; i < string.length() && i < 5 ;i++)
Upvotes: 2