高效实现:Java中的“Python For Else Loop”
2022-09-01 04:53:41
在Python中,这里描述了一个有效的循环实现。for .. else
示例代码:
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
}
有没有更好的实现类似于Java中的Python循环?for .. else