我正在练习制作自己的课程,最终我想建立一个包含这3辆车的车队并计算平均MPG。我很难把车开进车棚。我认为我的问题是实例变量,但我无法弄清楚该怎么做。
import java.util.Scanner;
class CarFleet {
Car car1;
Car car2;
Car car3;
CarFleet(first, second, third) {
car1 = first;
car2 = second;
car3 = third;
}
}
class Car {
double startMiles;
double endMiles;
double gallons;
Car(double initialMiles, double endingMiles, double tankGals) {
startMiles = initialMiles;
endMiles = endingMiles;
gallons = tankGals;
}
public double calculateMPG() {
return (endMiles - startMiles) / gallons;
}
}
class MPG {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//System.out.println("Initial miles for trip: ");
//double initMiles = scan.nextDouble();
//System.out.println("End miles for trip: ");
//double endMiles = scan.nextDouble();
//System.out.println("Gallons used for trip: ");
//double gals = scan.nextDouble();
Car Lambo = new Car(0, 335, 9.5);
String car1 = "Lambo";
System.out.println("Your " + car1 + " goes " + Lambo.calculateMPG() + " MPG");
Car Honda = new Car(0, 24, 2);
String car2 = "Honda";
System.out.println("Your " + car2 + " goes " + Honda.calculateMPG() + " MPG");
Car Eclipse = new Car(0, 48, 3);
String car3 = "Eclipse";
System.out.println("Your " + car3 + " goes " + Eclipse.calculateMPG() + " MPG");
CarFleet coolCars = new CarFleet(Lambo, Honda, Eclipse);
}
}
答案 0 :(得分:3)
CarFleet(Car first, Car second,Car third) {
this.car1 = first;
this.car2 = second;
this.car3 = third;
}
答案 1 :(得分:0)
问题出在这条线上。
CarFleet(first, second, third){
基本上,您定义了一个构造函数,但是没有给编译器提供关于 Type first
,second
和third
是什么的信息。
解决方案是使用
CarFleet(Car first, Car second, Car third) {
现在指定每个变量的 Type 。