Student ID(lintcode 455)

Description

Implement a class Class with the following attributes and methods:

  1. A public attribute students which is an 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

Interface

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.

    /**
     * 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
}

Solution

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
    public Class(int n) {
        students = new Student[n];
        for (int i = 0; i < n; ++i) {
            students[i] = new Student(i); 
        }
    }
}

results matching ""

    No results matching ""