【发布时间】:2021-05-11 16:21:36
【问题描述】:
我有一系列新车和二手车。我想在数组中搜索颜色为绿色的汽车。方法printAllCarsOfColor(String color) 将返回一个字符串,该字符串显示作为参数给出的颜色的所有汽车的信息。我试过了,但没有运气。
我有 Car 类,它是超类,NewCar 和 UsedCar 是子类。只有NewCar 类有Color 方法。我不知道如何打印出只有绿色的汽车。我知道 Color 方法不是为 Car 类定义的。
寻求帮助。谢谢!
我的代码:
public class CarDearlerShip
{
private Car[] aCar;
private int count;
private int car;
public CarDearlerShip()
{
aCar = new Car[80];
count = 0;
car = 0;
}
public void addNewCar(String model, int year, int price, String color)
{
aCar[count] = new NewCar(model, year, price, color);
count++;
}
public void addUsedCar(String model, int year, int price, boolean rusty)
{
aCar[count] = new UsedCar(model, year, price, rusty);
count++;
}
public String printReport()
{
String report = "---------------------------------------------\n";
report += "The list of availabel cars:\n\n";
for (int car = 0; car < count; car++)
report += aCar[car].toString() + "\n";
//System.out.println(report);
return report;
}
public String printAllCarsWithSellingPriceBelow(int price)
{
String printCars = "---------------------------------------------\n";
printCars += "The price for these cars are: \n\n";
for (int car = 0; car < count; car++)
{
if (aCar[car].aPrice < 1000); // The argument for the selling price
printCars +=aCar[car].getPrice();
}
return printCars;
}
public String printAllCarsOfColor(String color)
{
String printColor = "---------------------------------------------\n";
printColor += "The color : \n\n";
for (int car = 0; car < count; car++)
{
if (aCar[car].Color()==color);
printColor +=aCar[car];
}
return printColor;
}
}
The Test Class
public class TestDealer
{
public static void main(String[] args)
{
CarDearlerShip dealer= new CarDearlerShip();
dealer.addNewCar("GM Buick Century", 2004, 200000, "Silver");
dealer.addUsedCar("Toyota Corolla", 1999, 9000, true);
dealer.addNewCar("Honda Civic", 2004, 500, "Green");
dealer.addNewCar("BMW 320i", 2004, 35000, "Black");
dealer.addUsedCar("Toyota Sienna", 2000, 11000, false);
System.out.println(dealer.printReport());
System.out.println("**********************************");
//System.out.println(dealer.printAllCarsWithSellingPriceBelow(1000));
System.out.println("****************************************");
System.out.println(dealer.printAllCarsOfColor("Green"));
}
}
【问题讨论】:
-
分享您的
Car、UsedCar和NewCar来源? -
看起来像是一个错字:
if (aCar[car].Color()==color);后面不应该有分号 (;)。你应该使用.equals作为字符串。 -
我认为颜色应该是 Car 而不是 NewCar 的属性,这会让事情变得更容易。
标签: java arrays sorting arraylist methods