1
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?

1
  • So you want to change the or to an and? Commented Oct 24, 2017 at 6:00

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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++)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.