2013-03-13 162 views
1

我是Java新手,我开始使用ArrayLists。我正在尝试为学生创建一个ArrayList。每个学生都有不同的属性(name, id)。我想弄清楚如何用这个属性添加一个新的学生对象。以下是我有:在具有属性的数组列表中创建新对象

ArrayList <Student> studentArray; 
public Student(String name, int id) { 
    this.fname = name; 
    this.stId = id; 
} 
public Stromg getName() { 
    return fname; 
} 
public int getId() { 
    return stId; 
} 
public boolean setName(String name) { 
    this.fname = name; 
    return true; 
} 
public boolean setIdNum(int id) { 
    this.stId = id; 
    return true; 
} 
+0

那么究竟是什么真正的你的问题?出了什么问题? – uba 2013-03-13 04:51:58

+0

如何使用用户输入的名称和编号创建一个新的对象(学生)? – bardockyo 2013-03-13 04:52:45

+0

我认为'Stromg'意思是'String',否则不会编译(除非你实际上有一个潜伏在里面的'Stromg'类)。 – Makoto 2013-03-13 05:19:41

回答

6

你需要的是类似以下内容:

import java.util.*; 

class TestStudent 
{ 
    public static void main(String args[]) 
    { 
     List<Student> StudentList= new ArrayList<Student>(); 
     Student tempStudent = new Student(); 
     tempStudent.setName("Rey"); 
     tempStudent.setIdNum(619); 
     StudentList.add(tempStudent); 
     System.out.println(StudentList.get(0).getName()+", "+StudentList.get(0).getId()); 
    } 
} 

class Student 
{ 
    private String fname; 
    private int stId; 

    public String getName() 
    { 
     return this.fname; 
    } 

    public int getId() 
    { 
     return this.stId; 
    } 

    public boolean setName(String name) 
    { 
     this.fname = name; 
     return true; 
    } 

    public boolean setIdNum(int id) 
    { 
     this.stId = id; 
     return true; 
    } 
} 
+0

这正是我所期待的。谢谢你的帮助。 – bardockyo 2013-03-13 05:30:53

+0

@bardockyo:乐于帮忙。 :) – 2013-03-13 05:44:15

1
final List<Student> students = new ArrayList<Student>(); 
students.add(new Student("Somename", 1)); 

...等通过将合适的值给构造函数添加更多的学生

2

你实例化一个Student对象。

Student s = new Student("Mr. Big", 31); 

你把通过使用操作者.add()元件成ArrayList(或List)。 *

List<Student> studentList = new ArrayList<Student>(); 
studentList.add(s); 

你可以通过使用Scanner的必然System.in检索用户输入。

Scanner scan = new Scanner(System.in); 
System.out.println("What is the student's name?"); 
String name = scan.nextLine(); 
System.out.println("What is their ID?"); 
int id = scan.nextInt(); 

用循环重复此操作。这部分应作为练习留给读者。

*:还有其他选项,但add()只是将其添加到最后,这通常是您想要的。

+0

谢谢你的回应。我确切地知道你在说什么,但是我的项目中的get/set方法的用途是什么? – bardockyo 2013-03-13 05:00:26

+0

存取器和增变器。你确实想访问他们的名字和他们的ID的价值,但你真的需要改变它们吗?这可能是值得移除那些setters。 – Makoto 2013-03-13 05:03:07

+0

@bardockyo这些值还没有在Student对象中,你需要使用setter来设置它们 – 2013-03-13 05:03:15

相关问题