43

In Python there is an efficient for .. else loop implementation described here

Example code:

for x in range(2, n):
    if n % x == 0:
        print n, 'equals', x, '*', n/x
        break
else:
    # loop fell through without finding a factor
    print n, 'is a prime number'

In Java I need to write more code to achieve the same behavior:

finishedForLoop = true;
for (int x : rangeListOfIntegers){
    if (n % x == 0)
    {
        //syso: Some printing here
        finishedForLoop = false
        break;
    }
}
if (finishedForLoop == true){
    //syso: Some printing here
}

Is there any better implementation similar to Python for .. else loop in Java?

1
  • 6
    You can replace if (finishedForLoop == true) with if (finishedForLoop). No need to test for true, the if statement does that implicitly :) Commented Nov 7, 2013 at 8:21

5 Answers 5

82

It's done like this:

class A {
    public static void main(String[] args) {
        int n = 13;
        found: {
            for (int x : new int[]{2,3,4,5,6,7,8,9,10,11,12})
                if (n % x == 0) {
                    System.out.println("" + n + " equals " + x + "*" + (n/x));
                    break found;
                }
            System.out.println("" + n + " is a prime number");
        }
    }
}

$ javac A.java && java A
13 is a prime number
Sign up to request clarification or add additional context in comments.

3 Comments

Why the labeled break? There is only one loop to break out of.
@FredOverflow: it's not breaking out of the loop, but the enclosing block.
@FredOverflow To elaborate on Eric's comment: an unlabeled break would continue on the statement that follows the loop and still flow through the println statement.
15

When I need to do something like this, if no extra information is needed, I typically try to break it out into a separate method - which can then return true/false or alternatively either the value found, or null if it's not found. It doesn't always work - it's very context-specific - but it's something worth trying.

Then you can just write:

for (...) {
    if (...) {
       return separateMethod();
    }
}
return null; // Or false, or whatever

1 Comment

for cases when a different method is not ideal, you can always "break out" of the loop using a labelled break... but it is very rare to see this in practice.
2

No. That's the simplest. It's not that complicated, it's just syntax.

3 Comments

also, even if you find something "simpler", it will also be "smart". And "smart" is difficult-to-read
+1, Yes you are right, i am still interested in more "smart" solutions:-)
I don't see what's not smart about using the minimum syntax. To answer your question straight, no there is nothing simpler and there is nothing smarter.
2

Since java8 there is a way to write this with "nearly no" code:

if(IntStream.range(2, n).noneMatch(x -> n % x == 0)) {
   System.out.println(n + " is a prime number");
}

BUT: this would be less efficient than the classical looping-with-break-and-flag method.

Comments

-1

No, there is no mechanism like this in Java

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.