考虑以下代码:
package question.pkg2;
public class Car {
private int wheels;
private String color;
private boolean roadworthy;
public int year = 1982;
public Car() {
}
public Car(int numberOfWheels, String color, boolean roadworthy, int yearOfManufactured) {
wheels = numberOfWheels;
this.color = color;
this.roadworthy = roadworthy;
year = yearOfManufactured;
}
public int getNumberOfWheels() {
return wheels;
}
public String getColor() {
return color;
}
public String changeColor() {
return color;
}
public boolean getRoadworthiness() {
return roadworthy;
}
public String getYear(int checkYear) {
if (year < 1982) {
year = checkYear;
System.out.println("it is not considered roadworthy");
}
}
}
我的问题是要检查一年,但我收到了错误声明,这是什么意思?#34;缺少退货声明&#34;?
答案 0 :(得分:1)
您的方法签名是
public String getYear(int checkYear)
因此,您需要返回null
,String
。
这是你需要考虑的事情:
String
是一个正确的返回类型吗?roadworthy
字段,而在getYear
中,它会打印与“适于行驶”相关的消息;如果在year
中更改getYear
,是否还应更新roadworthy
?答案 1 :(得分:0)
你的方法:
public String getYear(int checkYear) {
if (year < 1982) {
year = checkYear;
System.out.println("it is not considered roadworthy");
}
}
如果希望该方法将年份作为String返回,则需要将int转换为String 所以它必须是这样的:
public String getYear(int checkYear) {
if (year < 1982) {
year = checkYear;
System.out.println("it is not considered roadworthy");
}
return Integer.toString(year);
}
或者,如果你只是想要写一个consol,如果年&lt; 1982年强> 所以它必须是这样的:
public void getYear(int checkYear) {
if (year < 1982) {
year = checkYear;
System.out.println("it is not considered roadworthy");
}
}
答案 2 :(得分:0)
您在getYear方法中缺少返回值。当您使用void之外的返回类型对某些方法进行十分转换时,必须始终从该方法返回一个cpmpatible值。否则你会得到那个错误。
public String getYear(int checkYear) {
if (year < 1982) {
year = checkYear;
System.out.println("it is not considered roadworthy");
}
return "some string value that you want to return";
}