gpt4 book ai didi

java - 如何使用另一个数组中的对象初始化新数组(我获取地址,而不是值)

转载 作者:行者123 更新时间:2023-12-02 10:54:20 25 4
gpt4 key购买 nike

我在初始化数组时遇到问题。它显示了一个新的内存地址数组,而不是值。我错了,但我找不到错误。这可能很容易,但我希望你能帮助我。

public static void searchCarByBrand(Car[] cars, char ch) {

System.out.println("the method searchCarByBrand was called with ch = " + ch);
int carsLenght = cars.length;
Car[] carsArray = new Car[carsLenght];

for(Car aCars : cars) {
System.out.println("this is for each");

if(getBrand().charAt(0) == ch) {
System.out.println("this is if");

for(int i = 0; i< carsArray.length; i++) {
carsArray[i] = new Car();
System.out.println("carsArray[" + i + "]: " + carsArray[i]);
}
}
}
}
public class Car {
private static String brand;
private String model;
// private String model;
private String color;
private int horsePower;
private String engineType;
private String gearBoxType;
private String dateOfManufacture;

}

   public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Car car1 = new Car("Mercedes", "slk", "blue", 199, "bnz", "r",
"18 August 2005");
Car car2 = new Car("peugeot", "206 cc", "blue", 165,"bnz", "r", "200");
Car car3 = new Car("peugeot", "206" , "red", 155, "bnz", "r", "2005");

Car[] carArray = new Car[3];
carArray[0] = car1;
carArray[1] = car2;
carArray[2] = car3;

System.out.println("this is the result from the 1st method:");
System.out.println("enter brand:");
char ch = scan.next().charAt(0);
searchCarByBrand(carArray,ch);

}

最佳答案

如果您想在控制台上打印,请尝试在汽车类中添加 public String toString() 方法。
另外,在您的数组中,您添加了一个空的汽车对象,因此它不会打印任何值

carsArray[i] = new Car(); System.out.println("carsArray[" + i + "]: " + carsArray[i]);

在汽车类中添加toString方法

    @Override
public String toString() {
return "Car{" +
"model='" + model + '\'' +
", color='" + color + '\'' +
", horsePower=" + horsePower +
", engineType='" + engineType + '\'' +
", gearBoxType='" + gearBoxType + '\'' +
", dateOfManufacture='" + dateOfManufacture + '\'' +
'}';
}

代码中似乎存在一些逻辑错误
if(aCars.getBrand().charAt(0) == ch)

carsArray[i] = new Car() aCars;

for(Car aCars:汽车) { System.out.println("这是针对每个的");

    if(aCars.getBrand().charAt(0) == ch) {
System.out.println("this is if");

for(int i = 0; i< carsArray.length; i++) {
carsArray[i] = aCars;
System.out.println("carsArray[" + i + "]: " + carsArray[i]);
}
}
}

}

关于java - 如何使用另一个数组中的对象初始化新数组(我获取地址,而不是值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51894046/

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