为学生分配宿舍java代码
时间: 2024-03-07 19:51:26 浏览: 25
好的,以下是一个简单的为学生分配宿舍的Java代码示例:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class DormitoryAllocation {
public static void main(String[] args) {
// 模拟学生数据
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("张三", 170, 60));
studentList.add(new Student("李四", 175, 70));
studentList.add(new Student("王五", 160, 50));
studentList.add(new Student("赵六", 180, 80));
studentList.add(new Student("钱七", 165, 55));
studentList.add(new Student("孙八", 185, 75));
// 随机分配宿舍
Random random = new Random();
int dormitoryNum = 3; // 宿舍数量
List<Dormitory> dormitoryList = new ArrayList<>();
for (int i = 0; i < dormitoryNum; i++) {
dormitoryList.add(new Dormitory(i+1));
}
for (Student student : studentList) {
int index = random.nextInt(dormitoryNum);
dormitoryList.get(index).addStudent(student);
}
// 输出宿舍分配结果
for (Dormitory dormitory : dormitoryList) {
System.out.println("宿舍" + dormitory.getNum() + "的学生有:");
for (Student student : dormitory.getStudentList()) {
System.out.println(student.getName());
}
System.out.println();
}
}
}
// 学生类
class Student {
private String name;
private int height;
private int weight;
public Student(String name, int height, int weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
public String getName() {
return name;
}
public int getHeight() {
return height;
}
public int getWeight() {
return weight;
}
}
// 宿舍类
class Dormitory {
private int num;
private List<Student> studentList;
public Dormitory(int num) {
this.num = num;
this.studentList = new ArrayList<>();
}
public int getNum() {
return num;
}
public List<Student> getStudentList() {
return Collections.unmodifiableList(studentList);
}
public void addStudent(Student student) {
studentList.add(student);
}
}
```
以上代码中,我们先定义了一个`Student`类和一个`Dormitory`类,分别表示学生和宿舍。然后,我们模拟了一些学生数据,并随机将它们分配到不同的宿舍中。最后,输出了宿舍分配结果。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)