【发布时间】:2019-06-06 21:34:16
【问题描述】:
对于 Arraylists 的赋值,我需要将一维数组更改为数组列表,这意味着将程序从 listName.length 修改为 listName.size() 等。
我在将我的数组列表动物声明为类方法时遇到问题。我这样做了:animals.get(x) = new Dog(name, age); 但我收到一个错误,它说左侧必须是一个变量。 new Cat(name, age); 和 new Bird(name, age); 上发生了同样的错误。
现在,我尝试创建一个字符串变量并分配给animals.get(x),然后将该变量分配给new Dog(name,age),这也不起作用,因为它希望我将new Dog(name, age) 更改为字符串(意思是更改我的变量名,比如说String string,到Dog string),当我这样做时,我回到了第一格,它要求我将变量改回字符串。
import java.util.ArrayList;
import java.util.Collection;
public class Database {
ArrayList<String> animals = new ArrayList<String>();
Database (int s) {
animals.size();
}//end of Database(s)
boolean addAnimal (int type, String name, int age) {
for (int x = 0; x < animals.size(); x++) {
if (animals.get(x) == null) {
if (type == 1) {
animals.get(x) = new Dog(name, age);
}//end of if
else if (type == 2) {
animals.get(x) = new Cat(name, age);
}//end of else if
else {
animals.get(x) = new Bird(name, age);
}//end of else
return true;
}//end of outer if
}//end of for loop
return false;
}//end of addAnimal(type, name, age)
Animal removeAnimal (String name) {
for (int x = 0; x < animals.size(); x++) {
if (animals.get(x).equals(null)) {
// If the spot in the array is null skip this index
}//end of if
else if (animals.get(x).equals(name)) {
String found = animals.get(x);
animals.at(x) = null;
System.out.print(found);
}//end of else if
}//end of for loop
return null;
}//end of removeAnimal(name)
}//end of class Database
由于我正在修改所有内容以适应数组列表,因此当用户选择添加动物时,我也必须修改上述方法。共有三种动物,狗、猫和鸟,它们都有自己的类。我m expecting the error'the left-hand side must be a variable' to disappear, and Ive 尝试寻找解决方法,但我似乎找不到与我的问题类似的解决方案。
编辑更新
我包含了我的 Database 类(具有 addAnimal 和 removeAnimal 方法的类)的完整代码。
【问题讨论】:
标签: java class oop variables arraylist