我的类车中的getYear,getMake和getModel方法收到此错误消息,因为显然它们没有被传递参数。在我看来,他们正在通过论证,但我仍然是Java的初学者,所以我不确定我搞砸了。
public class NextCar {
public static final void main(String args[]) {
//Creates objects from Car class
Car c = new Car ();
Car c1 = new Car ();
Car c2 = new Car ();
Car c3 = new Car ();
//First object
//Prints mileage
c.start();
c.moveForward(6);
c.moveBackward(2);
c.moveForward(4);
System.out.println ("The car went " + c.mileage() + " miles.");
//Second object
//Prints year of car
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
//Third object
//Prints year and make of car
c2.getYear(2055);
c2.getMake("Google");
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
//Fourth object
//Prints year, make, and model of car
c3.getYear(2060);
c3.getMake("Google");
c3.getModel("Smart");
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
c3.getMake() + " and the model is " + c3.getModel());
}
}
//creates Car class
class Car {
public int year = 0;
public String make = "";
public String model = "";
public int miles = 0;
public boolean power = false;
public void start() {
power = true;
}
public void moveForward(int mf) {
if (power == true) {
miles += mf;
}
}
public void moveBackward(int mb) {
if (power == true) {
miles -= mb;
}
}
public int mileage() {
return miles;
}
public int getYear(int y) {
year = y;
return year;
}
public String getMake(String ma) {
make = ma;
return make;
}
public String getModel(String mo) {
model = mo;
return mo;
}
}
答案 0 :(得分:1)
您的Car
类getYear
方法接受整数输入:
public int getYear(int y)
但在没有提供输入的情况下,您可以多次调用
System.out.println("The year of the car is " + c1.getYear());
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
这就是你错误的原因。
您可能需要两种方法getYear
(获取年份值)和setYear
(设置年份值),但您只定义了一种方法。可能这就是你所需要的:
public void setYear(int y) {
year = y;
}
public int getYear() {
return year;
}
答案 1 :(得分:0)
再看看这里:
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
getYear返回一个值。所以你可以做到
int year = c1.getYear(2050);
System.out.println("The year of the car is " + year);
与其他人相似。或者如Juned所说,使用合适的getter / setter