这是我的代码。
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;
}**因为当我运行程序时没有显示输出。
发布于 2020-08-04 19:22:41
continue语句跳过循环的当前迭代。
在您的代码中,i的每个值都为count >= 1 || countTwo >= 1,因此continue语句在外部循环的每次迭代中执行,一旦continue语句执行,它就跳回到循环的开始处,而不执行下面的语句。最终,循环的终止条件计算为false,因此循环中断。
在您的情况下绝对不会使用label,因为如果没有label,您的代码将以与使用label时完全相同的方式执行。
你的逻辑也是完全错误的。您可以简化代码,如下所示:
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 ) 发布于 2020-08-04 19:19:02
continue inner意味着从标记为inner的循环的下一次迭代开始继续执行,而不管这条语句在哪里(只是它可能只出现在所述循环中)。
发布于 2020-08-04 19:22:57
大家好,欢迎来到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;
}
...https://stackoverflow.com/questions/63245712
复制相似问题