2014-11-20 47 views
-1

我得到這個錯誤信息爲我的班車內我的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; 
} 
} 

回答

1

CargetYear方法取一個整數輸入:

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; 
} 
0

而且看這裏:

c1.getYear(2050); 
System.out.println("The year of the car is " + c1.getYear()); 

中得到年返回一個值。所以你可以做

int year = c1.getYear(2050); 
System.out.println("The year of the car is " + year); 

其他類似。或者如Juned所說,使用適當的獲得者/設定者

相關問題