高效实现:Java 中的“Python For Else Loop”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13069402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Efficient implementation for: "Python For Else Loop" in Java
提问by Michael
In Python there is an efficient for else loop implementation described here
在 Python 中,这里描述了一个高效的 for else 循环实现
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:
在 Java 中,我需要编写更多代码来实现相同的行为:
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?
Java 中是否有类似于 Python for else 循环的更好的实现?
回答by Dog
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
回答by Jon Skeet
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 alwayswork - it's very context-specific - but it's something worth trying.
当我需要做这样的事情时,如果不需要额外的信息,我通常会尝试将它分解成一个单独的方法 - 然后可以返回true
/false
或者或者返回找到的值,或者如果没有找到则返回null。它并不总是有效 - 它非常特定于上下文 - 但它值得尝试。
Then you can just write:
然后你可以写:
for (...) {
if (...) {
return separateMethod();
}
}
return null; // Or false, or whatever
回答by Joe
No. That's the simplest. It's not thatcomplicated, it's just syntax.
不,那是最简单的。没那么复杂,就是语法而已。
回答by Mathias Begert
Since java8 there is a way to write this with "nearly no" code:
由于 java8 有一种方法可以用“几乎没有”代码来编写它:
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.
但是:这会比经典的带有中断和标志的循环方法效率低下。
回答by Minion91
No, there is no mechanism like this in Java
不,Java 中没有这样的机制