这是我的代码。
public class TwinPrimeNumbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean isTwinPrime = false;
int count = 0, countTwo = 0, countThree = 0;
inner:
for (int i = 1; i <= 100; i++) {
for (int j = 1; j <= ((i + 2) / 2); j++) {
if (i % j == 0)
count++;
if ((i + 2) % j == 0)
countTwo++; // 1
}
if (count >= 1 || countTwo >= 1) { // This part is having a problem.
continue inner;
}
else {
for (int j = 1; j <= ((i + 1) / 2); j++) {
if ((i + 1) % j == 0) {
countThree++;
}
}
}
isTwinPrime = (i + 2) - i == 2;
if ( isTwinPrime == true && countThree >= 2 && count == 1 && countTwo == 1)
System.out.printf("Twin Primes: ( %d, %d ) %n", i, (i + 2));
count = 0;
countTwo = 0;
countThree = 0;
}
}
}
当这个语句出现在我的代码中时,我遇到了问题控制台中没有显示任何输出。continue语句是否阻止了下面的其他代码?
**if (count >= 1 || countTwo >= 1) {
continue inner;
}**
因为运行程序时没有输出。
continue
语句跳过循环的当前迭代。
在您的代码中,对于i
的每个值,count >= 1 || countTwo >= 1
都为true,因此continue
语句在外循环的每次迭代中执行,一旦continue
语句执行,它就会跳回循环的开始,而不执行下面的语句。最终,循环的终止条件计算为false,因此循环中断。
在您的案例中绝对没有使用标签,因为没有标签,您的代码将以与使用标签完全相同的方式执行。
你的逻辑也完全错了。您可以简化您的代码,如下所示:
public class TwinPrimeNumbers {
static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i < n; i++)
if (n % i == 0) return false;
return true;
}
public static void main(String args[]) {
int primeOne = -1;
for (int i = 1; i <= 100; i++) {
// if current number is prime and the differene between
// previously saved prime number and current number is 2,
// then we have a pair of Twin Primes
if (i - primeOne == 2 && TwinPrimeNumbers.isPrime(i)) {
System.out.printf("Twin Primes: ( %d, %d ) %n", primeOne, i);
// update primeOne
primeOne = i;
}
// if previous condition is false and current number is prime,
// save it in primeOne variable
else if (TwinPrimeNumbers.isPrime(i)) {
primeOne = i;
}
}
}
}
输出:
Twin Primes: ( 3, 5 )
Twin Primes: ( 5, 7 )
Twin Primes: ( 11, 13 )
Twin Primes: ( 17, 19 )
Twin Primes: ( 29, 31 )
Twin Primes: ( 41, 43 )
Twin Primes: ( 59, 61 )
Twin Primes: ( 71, 73 )
continue inner
意味着从标记为inner
的循环的下一次迭代开始继续执行,而不管该语句在哪里(除了它可能只出现在所述循环内部(。
大家好,欢迎来到StackOverflow!
continue
作为goto
的用例并不受欢迎,因为它代表了代码中无条件的跳转。
在这种情况下,考虑到continue
语句没有包含在多个循环中,您可以丢弃标签。代码变为:
int count = 0, countTwo = 0, countThree = 0;
for (int i = 1; i <= 100; i++) {
for (int j = 1; j <= ((i + 2) / 2); j++) {
if (i % j == 0)
count++;
if ((i + 2) % j == 0)
countTwo++; // 1
}
if (count >= 1 || countTwo >= 1) { // This part is having a problem.
continue;
}
...