public StudentLottery() {
ArrayList<Student> list = new ArrayList<Student>();
}
public void addStudents() {
Scanner keyboard=new Scanner(System.in);
String input;
String id;
String name;
Student s;
System.out.println("Enter? (y or n):");
input=keyboard.nextLine();
while (!(input.equals("n"))){
System.out.println("Name:");
name=keyboard.nextLine();
System.out.println("ID:");
id=keyboard.nextLine();
s=new Student(name,id);
if (!(list.contains(s)))
list.add(s);//error
System.out.println("Enter? (y or n):");
input=keyboard.nextLine();
}
}
list.add(s) 上发生错误,我认为 arrayLists 可以接受任何类型的对象,但这个 arraylist 只喜欢字符串,所以我不确定我应该做什么来解决这个问题,以便我的 arraylist 接受学生对象
jcreator 说找不到合适的添加方法
最佳答案
您在 StudentLottery
构造函数中声明的列表是一个本地变量,而不是字段。您无法在构造函数的范围之外访问它。也许您的意思是:
private ArrayList<Student> list; // i.e. list is a field
public StudentLottery() {
this.list = new ArrayList<Student>(); // initialize list in constructor
}
关于java - arraylist 没有适合 list.add 的方法(数组是对象类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198146/