使用Java编写程序实现(1)定义School类包含两个属性:学校名称name(String),在校人数num(int))
时间: 2024-01-20 12:04:11 浏览: 24
好的,下面是实现代码:
```java
public class School {
private String name;
private int num;
public School(String name, int num) {
this.name = name;
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
```
上面的代码定义了一个School类,包含了两个属性name和num,分别表示学校名称和在校人数。在类的构造函数中,我们可以初始化这两个属性的值,并在类中提供了对这两个属性进行读写操作的方法。
相关问题
使用Java编写程序实现(1)定义School类包含两个属性:学校名称name(String),在校人数num(int))(2)实现Comparable接口,按照学校人数排序。(3)采用TreeSet容器存储School类的三个对象。(4)使用Iterator,遍历输出容器中各School对象的学生人数)
好的,下面是实现代码:
```java
import java.util.Iterator;
import java.util.TreeSet;
public class School implements Comparable<School> {
private String name;
private int num;
public School(String name, int num) {
this.name = name;
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public int compareTo(School o) {
return this.num - o.num;
}
public static void main(String[] args) {
School s1 = new School("School A", 1000);
School s2 = new School("School B", 2000);
School s3 = new School("School C", 1500);
TreeSet<School> set = new TreeSet<>();
set.add(s1);
set.add(s2);
set.add(s3);
Iterator<School> iterator = set.iterator();
while (iterator.hasNext()) {
School school = iterator.next();
System.out.println(school.getNum());
}
}
}
```
上面的代码中,我们实现了Comparable接口,并实现了compareTo方法,按照学校人数进行排序。然后使用TreeSet容器存储三个School对象,并使用Iterator遍历输出每个School对象的学生人数。
编写程序实现: (1)定义School类,包含两个届性:学校名称name (String类型),在校人数num(int)(2)实现Comparable接口,按照学生人数排序: (3)采用Tree Set 容器存储School类的3个对象: (4)使用Iterator,遍历输出容器中各 School对象的学生人数。
以下是Java代码实现:
```
import java.util.Iterator;
import java.util.TreeSet;
public class School implements Comparable<School> {
private String name;
private int num;
public School(String name, int num) {
this.name = name;
this.num = num;
}
public String getName() {
return name;
}
public int getNum() {
return num;
}
@Override
public int compareTo(School o) {
return this.num - o.getNum();
}
public static void main(String[] args) {
School s1 = new School("School A", 1000);
School s2 = new School("School B", 500);
School s3 = new School("School C", 800);
TreeSet<School> set = new TreeSet<>();
set.add(s1);
set.add(s2);
set.add(s3);
Iterator<School> iterator = set.iterator();
while (iterator.hasNext()) {
School school = iterator.next();
System.out.println(school.getNum());
}
}
}
```
解释一下代码:
- 定义了一个 `School` 类,包含两个属性 `name` 和 `num`,分别表示学校名称和在校人数。
- 实现了 `Comparable` 接口,并覆写了 `compareTo` 方法,按照在校人数从小到大排序。
- 在 `main` 方法中,创建了三个 `School` 对象,并使用 `TreeSet` 存储,自动按照在校人数排序。
- 使用 `Iterator` 遍历 `set` 容器中的 `School` 对象,并输出其在校人数。