简体   繁体   English

arraylist没有适合list.add的方法(数组属于对象类型)

[英]arraylist no suitable methods for list.add (array is of object type)

    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();
    }

}

error occurs on list.add(s), I thought arrayLists could accept any type of object, but this arraylist only likes strings, so I'm unsure what I should be doing to fix this, so that my arraylist will accept student objects 在list.add(s)上发生错误,我以为arrayLists可以接受任何类型的对象,但是此arraylist只喜欢字符串,因此我不确定该怎么做以解决此问题,以便我的arraylist可以接受学生对象

jcreator says no suitable add method found jcreator说找不到合适的添加方法

The list you've declared in the StudentLottery constructor is a local variable, not a field. 您在StudentLottery构造函数中声明的列表是局部变量,而不是字段。 You can't access it beyond the scope of the constructor. 您不能超出构造函数的范围访问它。 Perhaps you meant: 也许您的意思是:

private ArrayList<Student> list;  // i.e. list is a field

public StudentLottery() {
    this.list = new ArrayList<Student>();  // initialize list in constructor
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM