已知学生Student拥有以下属性,学号,姓名,性别,年龄 班级Sclass拥有以下属性,班级编号,班级名称,班主任姓名 往hashmap中添加数据,其中学生作为key,班级作为value。 要求: 1 遍历hashmap,打印每组key和value的详细信息 2 统计每个班级的学生人数 3 统计班级的平均年龄
时间: 2023-04-12 20:01:24 浏览: 57
好的,我可以回答这个编程类的问题。
以下是lua closure factory的完整代码:
```
function createClosureFactory()
local count = 0
return function()
count = count + 1
return function()
return count
end
end
end
```
现在让我来回答你的问题:
1. 遍历hashmap,打印每组key和value的详细信息:
```
for student, sclass in pairs(hashmap) do
print("学生信息:")
print("学号:" .. student.id)
print("姓名:" .. student.name)
print("性别:" .. student.gender)
print("年龄:" .. student.age)
print("班级信息:")
print("班级编号:" .. sclass.id)
print("班级名称:" .. sclass.name)
print("班主任姓名:" .. sclass.teacher)
end
```
2. 统计每个班级的学生人数:
```
local classCount = {}
for student, sclass in pairs(hashmap) do
if not classCount[sclass.id] then
classCount[sclass.id] = 0
end
classCount[sclass.id] = classCount[sclass.id] + 1
end
for classId, count in pairs(classCount) do
print("班级编号为" .. classId .. "的班级有" .. count .. "名学生")
end
```
3. 统计班级的平均年龄:
```
local classAge = {}
for student, sclass in pairs(hashmap) do
if not classAge[sclass.id] then
classAge[sclass.id] = 0
end
classAge[sclass.id] = classAge[sclass.id] + student.age
end
for classId, age in pairs(classAge) do
local count = classCount[classId]
local average = age / count
print("班级编号为" .. classId .. "的班级平均年龄为" .. average)
end
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)