我的while循环进入无限循环,出了什么问题?

时间:2015-04-12 11:15:47

标签: java while-loop primes

我尝试编写BiggerThanPrime程序,该程序允许用户给出输入p,程序可以找到下一个最接近的素数(n),使得(n-p)的值最小。

这是我的代码:

static boolean Prime (int n){
    boolean NotPrime = true;
    boolean result = true;
    for (int i=2; i< n; i++){
        NotPrime = (n % i != 0);
        result = (result && NotPrime);
    }
    return result;
}

//Using Betrand's Postulate which states that there always exists at least one prime p s.t.a< p <2a
public static void main(String[] args) {
    int p = Integer.parseInt(args[0]);
    int k = p+1;
    while( k > p && k< 2*p){
        if( Prime(k) == true){
            System.out.println("the next bigger prime than "+ p + " is "+ k);
        } else{
            k++;
        }
    }
}

但是while循环进入无限循环。

结果是:

the next bigger prime than 20 is 23
the next bigger prime than 20 is 23
.
.
. 
(infinitely goes on) :(

我做错了什么?

6 个答案:

答案 0 :(得分:2)

一旦获得更大的素数,你需要打破循环,并且你需要在每次迭代中增加k,如下所示:

while( k > p && k< 2*p){
    if(Prime(k)){
        System.out.println("the next bigger prime than "+ p + " is "+ k);
         break;
     }           
    k++; 
}

还请注意,当Prime(k)返回一个布尔值时,不必再将它与true进行比较。

答案 1 :(得分:1)

一旦找到下一个素数,就应该从循环中断开:

    while( k > p && k< 2*p){
        if( Prime(k) == true){
            System.out.println("the next bigger prime than "+ p + " is "+ k);
            break;
        } else{
            k++;
        }               
    } 

答案 2 :(得分:1)

因为您没有在每次迭代时递增k

试试这个:

while( k > p && k< 2*p){
    if( Prime(k) == true){
        System.out.println("the next bigger prime than "+ p + " is "+ k);
     }           
      k++;
}

答案 3 :(得分:1)

 while( k > p && k< 2*p){
            if( Prime(k) == true){
                System.out.println("the next bigger prime than "+ p + " is "+ k);
            } else{
                k++;
            }               
        }  

一旦Prime(k)返回true,你就不会改变k的值,因此循环继续。

答案 4 :(得分:1)

  

( Prime(k) == true)时,它永远不会增加k的值。所以   它将进入无限循环。

你可以用这两种方式改变lop

方式1:

 while( k > p && k< 2*p){
        if( Prime(k) == true){
            System.out.println("the next bigger prime than "+ p + " is "+ k);
        } 
        k++;
    }

方式2:

 while( k > p && k< 2*p){
        if( Prime(k) == true){
            System.out.println("the next bigger prime than "+ p + " is "+ k);
            Break;
        } else{
            k++;
        }
  }

答案 5 :(得分:0)

 import java.util.*;

 public class index_page
{

    public static void main(String[] args) {
       Scanner keyB = new Scanner(System.in);

     String code = keyB.next();
          while (!code.equals("01") ||  code.equals("02")  ||  code.equals("00")  || code.equals("03")  ||  code.equals("04") ||  code.equals("05")){//Checking for erros in code from user
          System.out.println("Invalid code!! Try again");
             code = keyB.next(); 
            }
    }
}
相关问题