Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient implementation for: "Python For Else Loop" in Java

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?

like image 588
Michael Avatar asked Oct 25 '12 13:10

Michael


People also ask

Can we use else for for loop in Java?

In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.

Can you do a Java for loop in Python?

In Python the for loop can also iterate over any sequence such as a list, a string, or a tuple. Java also provides a variation of its for loop that provides the same functionality in its so called for each loop.

Which loop is best in Java?

If the number of iteration is fixed, it is recommended to use for loop. If the number of iteration is not fixed, it is recommended to use while loop. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.

Which loop is better for or while in Java?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.


1 Answers

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 
like image 115
Dog Avatar answered Sep 22 '22 21:09

Dog