您好我正在尝试为类赋值创建递归方法.作业如下:
在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
Run Code Online (Sandbox Code Playgroud)
第一个错误
if (age = n)
Run Code Online (Sandbox Code Playgroud)
这应该是
if (age == n)
Run Code Online (Sandbox Code Playgroud)
既然你在比较,而不是分配.
它说"布尔转换"的原因是赋值语句age = n返回新值age,即int.并且预期if语句采用布尔值.
第二个错误
对于"意外类型",将最后一行更改return rec(int n);为return rec(n);.应该没有int那里,这就是你得到"意外类型"的原因.
第三个错误
修复这些错误后,请检查您的逻辑.您当前的递归函数不会执行它应该执行的操作.