数组中的最后一个对象替换所有其他对象
Last Object in Array Replacing All Other Objects
当我创建这个数组时,我创建的最后一个对象替换了之前的两个对象。
public class Main
{
public static final int NUM_CARS = 3;
private static Scanner scanner;
public static void main(String[] args)
{
Car[] cars;
cars = new Car[NUM_CARS];
cars[0] = new Car( "Toyota Camry", 3400 );
cars[1] = new Car( "Ford F-150", 5000 );
cars[2] = new Car( "Honda Civic", 3000 );
System.out.println( cars[0] );
System.out.println( cars[1] );
System.out.println( cars[2] );
这应该打印每辆汽车的品牌和型号及其 MPG。但它最终打印了第三个对象(Civic)三次。这是构造函数:
public class Car
{
private static String model; // Car make and model (e.g. "BMW 328i)
private static double mpg; // Car's miles per gallon
private static double milesDriven; // The total miles driven (odometer)
private static double fuelGallons; // The amount of fuel in the tank (in gallons)
public Car( String carModel, int weight )
{
model = carModel;
if ( weight > 4000 )
mpg = 20.0;
else
mpg = 30.0;
milesDriven = 7;
fuelGallons = 15;
}
我认为 "new" 不会覆盖数组中的每个元素,但事实并非如此。
提示:忘记 static 关键字,它不好
您 Car
class 中的所有字段都声明为静态的。这意味着这 4 个字段由所有 Car
个实例共享。
将 Car
class 的开头替换为:
public class Car
{
private String model; // Car make and model (e.g. "BMW 328i)
private double mpg; // Car's miles per gallon
private double milesDriven; // The total miles driven (odometer)
private double fuelGallons; // The amount of fuel in the tank (in gallons)
解决您的问题。
当我创建这个数组时,我创建的最后一个对象替换了之前的两个对象。
public class Main
{
public static final int NUM_CARS = 3;
private static Scanner scanner;
public static void main(String[] args)
{
Car[] cars;
cars = new Car[NUM_CARS];
cars[0] = new Car( "Toyota Camry", 3400 );
cars[1] = new Car( "Ford F-150", 5000 );
cars[2] = new Car( "Honda Civic", 3000 );
System.out.println( cars[0] );
System.out.println( cars[1] );
System.out.println( cars[2] );
这应该打印每辆汽车的品牌和型号及其 MPG。但它最终打印了第三个对象(Civic)三次。这是构造函数:
public class Car
{
private static String model; // Car make and model (e.g. "BMW 328i)
private static double mpg; // Car's miles per gallon
private static double milesDriven; // The total miles driven (odometer)
private static double fuelGallons; // The amount of fuel in the tank (in gallons)
public Car( String carModel, int weight )
{
model = carModel;
if ( weight > 4000 )
mpg = 20.0;
else
mpg = 30.0;
milesDriven = 7;
fuelGallons = 15;
}
我认为 "new" 不会覆盖数组中的每个元素,但事实并非如此。
提示:忘记 static 关键字,它不好
您 Car
class 中的所有字段都声明为静态的。这意味着这 4 个字段由所有 Car
个实例共享。
将 Car
class 的开头替换为:
public class Car
{
private String model; // Car make and model (e.g. "BMW 328i)
private double mpg; // Car's miles per gallon
private double milesDriven; // The total miles driven (odometer)
private double fuelGallons; // The amount of fuel in the tank (in gallons)
解决您的问题。