PrimeAgeChecker只返回false

时间:2014-03-18 22:29:01

标签: java

我的PrimeAgeChecker对于每个年龄段的人都会返回假,即使是那些最优秀的年龄,我似乎无法弄清楚为什么会这样。我是编程新手,我将不胜感激。有人能指出我正确的方向吗?

public class Employee {
// fields
String name;
int age;
Department department;
PrimeAgeChecker checks;


// constructors
public Employee(Department department, String name, int age) {
    this.name = name;
    this.age = age;
    this.department = department;

}

public String getName() {
    return name;
}


public int getAge() {
    return age;
}


public Department getDepartment() {
    return department;
}

public boolean getChecker(){
    return PrimeAgeChecker.isPrime;
}


public String toString(){
    StringBuffer sb = new StringBuffer();
    sb.append(getDepartment() + " ");
    sb.append("\t");
    sb.append(getName());
    sb.append("\t");
    sb.append(getAge());
    sb.append("\t");
    sb.append(getChecker());

    return sb.toString();
}
}


public class PrimeAgeChecker {

static int ages;
public static boolean isPrime = false;



PrimeAgeChecker(Employee age) {
    ages = age.getAge();
}

public boolean check() {

    if ((ages % 2 == 0) || (ages == 2))
    {
        isPrime = true;
    }

return isPrime;

}

}

固定解决方案

public boolean getChecker(){
    PrimeAgeChecker primeAgeChecker = new PrimeAgeChecker();
    return primeAgeChecker.isPrime(getAge());
}

public class PrimeAgeChecker {

static int ages;
public boolean isPrime;


public static void getAge(Employee e){
    ages = e.getAge();
}


boolean isPrime(int ages) {
    if (ages%2==0) return false;
    for(int i=3;i*i<=ages;i+=2) {
        if(ages%i==0)
            return isPrime = false;
    }
    return isPrime = true;
}
}

1 个答案:

答案 0 :(得分:3)

问题在于,当您调用getChecker()时,您将返回PrimeAgeChecker.isPrime,它返回静态变量isPrime的值。声明isPrime为false,导致PrimeAgeChecker始终返回false。

您需要做的是创建PrimeAgeChecker的实例,传入年龄,然后调用check的{​​{1}}方法。

您的PrimeAgeChecker方法可能如下所示:

getChecker

请记住,正如其他人所提到的,检查年龄是否为素数的逻辑也存在缺陷。