gpt4 book ai didi

java - : "Python For Else Loop" in Java 的高效实现

转载 作者:IT老高 更新时间:2023-10-28 21:09:52 25 4
gpt4 key购买 nike

在 Python 中有一个高效的 for ..else 循环实现描述 here

示例代码:

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'

在 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
}

有没有更好的类似于Python中的for ..else循环在Java中的实现?

最佳答案

这样做是这样的:

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

关于java - : "Python For Else Loop" in Java 的高效实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13069402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com