gpt4 book ai didi

java - 不兼容的类型 : Cannont be converted

转载 作者:行者123 更新时间:2023-12-01 17:48:37 26 4
gpt4 key购买 nike

所以我创建了三个类; PetStore、宠物和鸟类。 PetStore 类是主类,pet 扩展 PetStore,然后 Bird 扩展自 Pet

现在我使用以下代码创建了一个驱动程序类。

public class Main{
public static void main(String[] args){
//create a pet objects
Bird macaw = new Bird("hyacinth macaw", 300.99, 48.0);

//create a pet store
PetStore happyPetsInc = new PetStore();

//add the pets to the pet store
happyPetsInc.addPet(macaw);

我正在尝试将鸟对象添加到 PetStore 中的数组列表中。

我收到错误:“不兼容的类型:Bird 无法转换为 java.lang.String”

有人标记了这一点并说要发布 PetStore 和 Bird 类,所以这里是:

public class PetStore
{
//varibles
String pet;

//ArrayList
ArrayList<String> Pets = new ArrayList<String>();

//constructor
public PetStore(){

}

/**
* add the paramameter to the ArrayList
* @param pet
* @return void
*/
public void addPet(String pet){
Pets.add(pet);
}

/**
* removes the paramater to the ArrayList
* @param pet
* @return true(success) false(failure)
*/
public boolean sellPet(String pet){
this.pet = pet;
if (Pets.contains(pet)){
Pets.remove(pet);
return true;
}else{
return false;
}
}

/**
* counts the number of elements in the ArrayList
* @param none
* @return int, the number of the elements in Pets
*/
public int getInventoryCount(){
return Pets.size();
}

/**
* displays information about the pets in the ArrayList
* @param none
* @return void
*/
public String toString(){
for (int i = 0; i < Pets.size(); i++){
System.out.println("Pet #" + (i + 1));
String index = Pets.get(i);
return index.toString();
}
return "\n";
}
}
public class Bird extends Pet
{
//varibale
double wingspan;
//constuctor
public Bird(String species, double cost, double wingspan){
super(species, cost);
this.wingspan = wingspan;
}

/**
* Sets the wingspan of the bird
* @param wingspan
* @return none
*/
public void setWingspan(double wingspan){
this.wingspan = wingspan;
}

/**
* Gets the wingspan of the bird
* @param none
* @return double
*/
public double getWingspan(){
return this.wingspan;
}

/**
* Displays strings describing the bird
* @param none
* @return String
*/
public String toString(){
return "Species: " + species + "\nCost: $" + cost + "\nBird (Wingspan: " + wingspan + " inches)";
}
}

最佳答案

面向对象编程的思想是,用类和类的实例(对象)来表示现实生活中的对象。因此,PetStore 是关于宠物的,而不是字符串。所以这样做:

在 PetStore 中替换

ArrayList<String> Pets ...
addPet(String pet)...
sellPet(String pet)...

ArrayList<Pet> Pets
addPet(Pet pet)
sellPet(Pet pet)

另外,在 PetStore.toString() 中替换

String index = Pets.get(i);

Pet index = Pets.get(i);

关于java - 不兼容的类型 : Cannont be converted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60825223/

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