定义一个Teacher类,有姓名和学科2个属性,之后创建3个teacher对象并赋值,然后存入集合中,用曾强for遍历集合,控制台打印每个老师的信息
时间: 2024-01-18 20:04:19 浏览: 66
好的,这是一个简单的Java编程题目。下面是代码实现:
```java
import java.util.ArrayList;
class Teacher {
private String name;
private String subject;
public Teacher(String name, String subject) {
this.name = name;
this.subject = subject;
}
public String getName() {
return name;
}
public String getSubject() {
return subject;
}
public void setName(String name) {
this.name = name;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Teacher> teachers = new ArrayList<>();
Teacher teacher1 = new Teacher("张三", "数学");
Teacher teacher2 = new Teacher("李四", "英语");
Teacher teacher3 = new Teacher("王五", "物理");
teachers.add(teacher1);
teachers.add(teacher2);
teachers.add(teacher3);
for (Teacher teacher : teachers) {
System.out.println("姓名:" + teacher.getName() + ",学科:" + teacher.getSubject());
}
}
}
```
输出结果如下:
```
姓名:张三,学科:数学
姓名:李四,学科:英语
姓名:王五,学科:物理
```
阅读全文