函数接口定义: class Student{ } 裁判测试程序样例: import java.util.ArrayList; public class Main{ private ArrayList slist = new ArrayList(); public void addStudent(Student s){ this.slist.add(s); } public void showStudent(){ for(Student s:slist){ System.out.println(s); } } public static void main(String[] args) { Main t = new Main(); t.addStudent(new Student("2016001","rose",18)); t.addStudent(new Student("2016002","hunifu",19)); t.addStudent(new Student("2016003","britsh",20)); t.addStudent(new Student("2016004","sunni",17)); t.showStudent(); } } /* 请在这里填写答案 */
时间: 2024-04-10 10:26:49 浏览: 118
这段代码中,需要定义一个`Student`类,包含学号、姓名和年龄三个属性。可以使用以下代码实现:
```java
class Student{
private String id;
private String name;
private int age;
public Student(String id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString(){
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
```
然后在`Main`类中定义`addStudent()`方法和`showStudent()`方法,用于添加学生和展示学生信息。完整代码如下:
```java
import java.util.ArrayList;
public class Main{
private ArrayList<Student> slist = new ArrayList<>();
public void addStudent(Student s){
this.slist.add(s);
}
public void showStudent(){
for(Student s: slist){
System.out.println(s);
}
}
public static void main(String[] args) {
Main t = new Main();
t.addStudent(new Student("2016001","rose",18));
t.addStudent(new Student("2016002","hunifu",19));
t.addStudent(new Student("2016003","britsh",20));
t.addStudent(new Student("2016004","sunni",17));
t.showStudent();
}
}
```
这样就可以创建`Main`对象并调用`addStudent()`方法来添加学生,然后调用`showStudent()`方法来展示学生信息。
阅读全文