创建实例并将它们存储在数组中

时间:2012-03-24 14:49:29

标签: java arrays

我有一个学生班,每个创建的学生实例都需要存储在一个数组中。属性可以在程序中给出,也可以从用户输入中读取。我是否可以扩展main()方法来存储它?我被卡住了。

这是我的学生班级代码:

public class student {

    int   studentID;
    String studentName,gender,course;
 /** set the student name
  * @param studentName
 */
 public  void        setName(String studentName){
this.studentName = studentName;
 }
  /**
  * set student ID number
  * @param studentID 
   */
   public  void        setNewId(int studentID){
   this.studentID = studentID;
  }
   /**
   * Set student gender
   * @param gender 
   */
   public void setGender(String gender){
  this.gender = gender;
 }
 /**
  * set the course
  * @param course 
  */
   public  void        setCourse(String course){
   this.course = course;
 }
 /**
  *Gets the Student's ID Number.
  *@return IdNumber Student ID Number.
  */
  public  int      getIdNumber(){
return studentID;
 }

  /**
  *Gets the Student's Name.
  *@return studentName Student Name.
  */
 public  String      getName(){
return studentName;
 }
 /**
  * Get student gender
  * @return 
   */
 public String getGender(){
  return gender;
 }
 /**
  *Gets the Student's Course.
  *@return course Student Course.
  */

  public  String     getCourse(){
return course;
  }
  /**
  *Prints Student Informations.
  *@return Student ID Number, name, gender and course.
    */

  public void printStudent(){
 System.out.print(studentID+""+studentName+""+gender+""+course);
}
}

这是我的main()方法的主类需要数组:

public class SMSMain {
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
    // Create an instance of student object

    student a = new student();
    a.studentName = "Maria";
    a.studentID = 1236;
    System.out.println("Student Name:" + a.studentName);
    System.out.println("Student ID:" + a.studentID);
}
}

1 个答案:

答案 0 :(得分:-1)

您需要启动数组并在循环内创建对象。

   Student[] students;
    System.out.println("Enter number of students :");


    DataInputStream in = new DataInputStream(System.in);
    int n = in.readInt();
    students = new Student[n];
    for(int i=0; i<n ;i++) {
        students[i] = new Student();
        System.out.println("Name:");
        students[i].setName(in.readLine());
        System.out.println("Id:");
        students[i].setNewId(in.readInt());
     }