In Python c'è un efficace per l'attuazione altro ciclo descritto hereefficiente implementazione per: "Python per Else Loop" in Java
codice Esempio:
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 ho bisogno di scrivere codice più per ottenere lo stesso comportamento:
finishedForLoop = true;
for (int x : rangeListOfIntegers){
if (n % x == 0)
{
//syso: Some printing here
finishedForLoop = false
break;
}
}
if (finishedForLoop == true){
//syso: Some printing here
}
Esiste un'implementazione migliore simile a Python per il ciclo alternativo in Java?
È possibile sostituire 'if (finishedForLoop == true)' con 'if (finishedForLoop)'. Non c'è bisogno di testare per 'true', l'istruzione' if' lo fa implicitamente :) – fredoverflow