我有一个编写带有构造函数的类的赋值+各种方法将值返回给主类.
由于错误,我的代码永远无法正确编译:无法找到简单或非法的表达式启动.
我相信我从根本上误解了如何构造一个构造函数,究竟主要方法是什么,以及一个类如何调用另一个类.
分配:
假设您获得了以下Driver类,其中包含一个main方法:
public class Driver {
public static void main(String[] args) {
double distance = 400.48;
double fuel = 21.4;
AutoTrip myTrip = new AutoTrip(distance, fuel);
System.out.print("My car traveled " + myTrip.getDistance() + " miles");
System.out.println("on " + myTrip.getFuel() + " gallons of gasoline.");
double mileage = myTrip.getMPG(); // get miles per gallon
System.out.println("My mileage was " + mileage + ".");
}
}
Run Code Online (Sandbox Code Playgroud)
*现在假设执行主要产生以下输出:我的汽车在21.4加仑汽油上行驶了400.48英里.
我的里程是18.714018691588787.
实现AutoTrip类,以便生成指示的输出.*
我的代码:
public class AutoTrip {
public AutoTrip(double distance, double fuel){
this.distance = distance;
this.fuel = fuel;
}
public double getDistance(){
return distance;
}
public double getFuel(){
return fuel;
}
public double getMPG(){
return distance / fuel;
}
}
Run Code Online (Sandbox Code Playgroud)
您忘记在AutoTrip类中添加变量
public class AutoTrip {
private double distance; // Missing var
private double fuel; // Missing var
public AutoTrip(double distance, double fuel) {
this.distance = distance;
this.fuel = fuel;
}
public double getDistance() {
return distance;
}
public double getFuel() {
return fuel;
}
public double getMPG() {
return distance / fuel;
}
}
Run Code Online (Sandbox Code Playgroud)