简体   繁体   English

计算素数的方法 - [JAVA]

[英]Method to calculate prime numbers - [JAVA]

I need to build a method that calculates a prime number for my homework. 我需要构建一个计算家庭作业素数的方法。 I implemented the algorithm proposed by my professor but it's not working. 我实施了我的教授提出的算法,但它不起作用。

Eclipse gives the message: The local variable prime may not have been initialized and does not compile. Eclipse给出了消息: The local variable prime may not have been initialized且无法编译。

Can someone help me? 有人能帮我吗?

public static boolean itsPrime(int nbTest){

    boolean prime;

    if (nbTest <= 1){
         prime = false;
    } else if (nbTest == 2){       // Two is the only even number that is prime
        prime = true;
    } else if ((nbTest != 2) && (nbTest % 2 == 0)){    // If it's even and different than two it is not prime
        prime = false;
    } else {
        for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){ 
            if (nbTest % i == 0){
                prime = false;
            } else {
                prime = true;
            }
        }   
    }

    return prime;
}   

Just initialise it when you declare the variable. 只需在声明变量时初始化它。 EG 例如

boolean prime = false;

You did not initialize the variable prime in your code. 您没有在代码中初始化变量prime By just looking at it, you saw that every branch of the if statement assigns a value to prime . 通过查看它,您看到if语句的每个分支都为prime赋值。 However, there is one exceptional case, what if the for loop doesn't get executed? 但是,有一个例外情况,如果for循环没有被执行怎么办? Then the value of prime is unknown! 那么prime的价值是未知的! So that's why the error appears. 这就是错误出现的原因。

I guess you want to return false if the loop doesn't get executed so just initialize prime with false when you declare it: 我想如果循环没有被执行则要返回false ,所以只需在声明时使用false初始化prime

boolean prime = false;

To make your code better, instead of just assigning values to prime , you can just return! 为了使您的代码更好,而不是仅仅为prime指定值,您只需返回! Let me show you the full code: 让我告诉你完整的代码:

public static boolean itsPrime(int nbTest){

    boolean prime = false;

    if (nbTest <= 1){
         return false;
    } else if (nbTest == 2){       // Two is the only even number that is prime
        return false;
    } else if ((nbTest != 2) && (nbTest % 2 == 0)){    // If it's even and different than two it is not prime
        return false;
    } else {
        for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){ 
            if (nbTest % i == 0){
                prime = false;
            } else {
                prime = true;
            }
        }   
    }

    return prime;
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM