Student ID

题目:

Implement a class Class with the following attributes and methods:

A public attribute students which is a array of Student instances.
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

分析:

这个题目很好用,需要记住以下几点

1. 创建数组的时候用 Student[] students;
2. students = new Student[n]; 这个很厉害,你用new开一个空间的时候就可以用变量名给size!!
很重要!很重要!很重要!!!
3. 构造函数没有函数类型,目测是void,也不用return

解法:

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.
    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 ""