2013-03-13 160 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

相關問題