gpt4 book ai didi

java - 如何在构造函数中使用 Car 对象引用?

转载 作者:行者123 更新时间:2023-12-01 23:05:37 29 4
gpt4 key购买 nike

我正在练习制作自己的类(class),最终我想制作一个包含这 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);
}
}

最佳答案

像这样

CarFleet(Car first, Car second,Car third) {
this.car1 = first;
this.car2 = second;
this.car3 = third;
}

关于java - 如何在构造函数中使用 Car 对象引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22818474/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com