用Scala面向对象方式实现学生管理系统,使用字典把学生姓名,QQ,微信的信息封装,使用列表list装学生信息,实现对字典的增删改查
时间: 2024-10-16 20:07:49 浏览: 55
在Scala中,我们可以使用`case class`创建简单的对象来表示学生,并利用`Map`和`List`数据结构来构建一个学生管理系统。首先,我们定义一个名为`Student`的`case class`:
```scala
case class Student(name: String, qq: String, wechat: String)
```
然后,我们可以使用`Map`存储学生的详细信息,比如一个键值对的形式:
```scala
val students: Map[String, Student] = Map(
"张三" -> Student("张三", "1234567890", "wx_123"),
"李四" -> Student("李四", "0987654321", "wx_456")
)
```
接下来,我们需要实现基本的增删改查操作:
### 添加学生(Add)
```scala
def addStudent(newStudent: Student): Unit = {
students += (newStudent.name -> newStudent)
}
// 示例
addStudent(Student("王五", "5555555555", "wx_567"))
```
### 删除学生(Delete)
```scala
def deleteStudent(name: String): Boolean = {
students.remove(name).isDefined
}
// 示例
if (deleteStudent("张三")) println(s"${name}已从系统中删除")
```
### 修改学生信息(Update)
```scala
def updateStudentInfo(name: String, updatedStudent: Student): Boolean = {
students.get(name) match {
case Some(student) => students.update(name, updatedStudent); true
case None => false
}
}
// 示例
updateStudentInfo("王五", Student("王五", "6666666666", "wx_789"))
```
### 查询学生信息(Find or Search)
```scala
def getStudentInfo(name: String): Option[Student] = {
students.get(name)
}
// 示例
getStudentInfo("李四") match {
case Some(student) => println(s"${student.name}'s QQ: ${student.qq}")
case None => println(s"No student named ${name}.")
}
```
阅读全文