递归方法给我错误

时间:2014-07-26 00:11:52

标签: java recursion

您好我正在尝试为类赋值创建一个递归方法。作业如下:

在Person类中实现一个方法,该方法使用递归基于以下公式计算指标m:

m(年龄)= 1 + 1/2 + 1/3 + 1/4 + 1/5 ... + 1 /年龄

我之前已经成为了这个人。所以一切正常。但是在它中实现这种递归方法会给我带来错误。我在递归方法中的if语句表示不兼容的类型:int无法转换为Boolean。我没有看到它认为我在做布尔变量转换的地方。另外,我在我的方法中进行了递归,它表示意外类型。

/**
 *
 * @author Randy
 */
public class Person2 {//begin class
    //declare variables
    String name;
    int year_of_birth;
    boolean isStudying;
    boolean isEmployed;
    int age;
    int result;

public Person2(boolean isEmployed, boolean isStudying){//begin constructor
    this.isEmployed = isEmployed;
    this.isStudying = isStudying;
}//end constructor

public Person2(){//begin constructor
    this.isEmployed = false;
    this.isStudying = false;
}//end constructor

public int getYear(){//get year method
        return year_of_birth;
}//end method

public String getName(){//get name method
        return name;
}//end method

public boolean getEmployed(){//get employed method
        return isEmployed;
}//end method

public boolean getStudying(){//get employed method
        return isStudying;
    }//end method

public int getAge(int year_of_birth){//get year method
        age = 2014 - year_of_birth;
    return age;
}//end method

public int rec(int n){//recursive method
    n++;
    result = 1 / n;
    if (age = n){
        return age;
    }
    return rec(int n);
}

public String getStatus(int age) { //begin method
    this.age = age;
    if (age <= 30 && isStudying == true && isEmployed == false) {
        System.out.println(name + " is a student");
    } else if (age >= 30 && age <= 65 && isStudying == false && isEmployed == true) {
        System.out.println(name + " is an employee");
    } else if (age >= 65 && isStudying == false && isEmployed == false) {
        System.out.println(name + " is retired");
    } else {
        System.out.println(name + " is something else");
    }
    return ("");
} //end method

public void setName(String name){//set name method
        this.name = name;
}//end method

public void setYear (int year){//set year method
        this.year_of_birth = year;
}//end method

public void setEmployed(boolean employed){//set employed method
        this.isEmployed = employed;
}//end method

public void setAge (int age){//set year method
        this.age = age;
}//end method
}//end class

2 个答案:

答案 0 :(得分:5)

第一次错误

if (age = n)

这应该是

if (age == n)

因为您正在进行比较,而不是分配。

它说&#34;布尔转换&#34;是赋值语句age = n返回age的新值,即int。并且它期望if语句采用布尔值。

第二次错误

对于&#34;意外类型&#34;,将最后一行从return rec(int n);更改为return rec(n);。那里不应该是int,这就是为什么你得到#34;意想不到的类型&#34;。

第三次错误

修复这些错误后,请检查您的逻辑。您当前的递归函数不会执行它应该执行的操作。

答案 1 :(得分:0)

您的程序有一些错误:

  • 您的陈述

if (age = n)

应该是

if (age == n).
  • 变量result is type int因此,对于n的所有值,结果为0或1。 * return rec(int n)

应该是

return rec(n)

  • 检查您的递归逻辑