Wednesday, February 3, 2016

Student ID

Student ID

Implement a class Class with the following attributes and methods:
  1. A public attribute students which is a array of Student instances.
  2. A constructor with a parameter n, which is the total number of students in this class. The constructor should create n Student instances and initialized with student id from 0 ~ n-1


Example
Class cls = new Class(3)
cls.students[0]; // should be a student instance with id = 0
cls.students[1]; // should be a student instance with id = 1
cls.students[2]; // should be a student instance with id = 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Student {
    public int id;
    
    public Student(int id) {
        this.id = id;
    }
}

public class Class {
    /**
     * Declare a public attribute `students` which is an array of `Student`
     * instances
     */
    // write your code here.
    public Student[] students;
     
    /**
     * Declare a constructor with a parameter n which is the total number of
     * students in the *class*. The constructor should create n Student
     * instances and initialized with student id from 0 ~ n-1
     */
    // write your code here
    Class(int n) {
        students = new Student[n];
        for (int i = 0; i < n; i++) {
            students[i] = new Student(i);
        }
    }
    
}