1.录入几位学生信息(姓名,学号,饭卡余额),并保存到student.txt文件中;2.能够依据学号对饭卡充值,每次充值的金额为10的倍数;3.能够按照学号查询饭卡余额,如果谁的余额少于10元,就给出充值提示。要求:软件至少应具有“输入初始数据”、“饭卡充值”、“查询余额”、“退出”4项菜单。
时间: 2023-12-25 20:06:38 浏览: 61
data/students.txt 学生信息表
好的,下面是Python代码实现:
```python
# 定义学生类
class Student:
def __init__(self, name, id, balance):
self.name = name
self.id = id
self.balance = balance
# 返回学生信息字符串
def __str__(self):
return f"{self.name}\t{self.id}\t{self.balance}\n"
# 读取学生信息文件
def read_students(filename):
students = []
with open(filename, "r") as file:
lines = file.readlines()
for line in lines:
name, id, balance = line.strip().split("\t")
student = Student(name, id, int(balance))
students.append(student)
return students
# 保存学生信息文件
def save_students(filename, students):
with open(filename, "w") as file:
for student in students:
file.write(str(student))
# 根据学号查询学生
def find_student(students, id):
for student in students:
if student.id == id:
return student
return None
# 录入学生信息
def input_students(students):
name = input("请输入学生姓名:")
id = input("请输入学生学号:")
balance = int(input("请输入学生饭卡余额:"))
student = Student(name, id, balance)
students.append(student)
# 饭卡充值
def recharge_balance(students):
id = input("请输入学生学号:")
student = find_student(students, id)
if student:
amount = int(input("请输入充值金额(10的倍数):"))
if amount % 10 == 0:
student.balance += amount
print(f"充值成功,当前余额为{student.balance}元。")
else:
print("充值金额必须为10的倍数!")
else:
print("该学生不存在!")
# 查询余额
def check_balance(students):
id = input("请输入学生学号:")
student = find_student(students, id)
if student:
print(f"{student.name}的饭卡余额为{student.balance}元。")
if student.balance < 10:
print("余额不足,请及时充值!")
else:
print("该学生不存在!")
# 主函数
def main():
filename = "student.txt"
students = read_students(filename)
while True:
print("请选择操作:")
print("1. 输入初始数据")
print("2. 饭卡充值")
print("3. 查询余额")
print("4. 退出")
choice = input("请输入序号:")
if choice == "1":
input_students(students)
save_students(filename, students)
elif choice == "2":
recharge_balance(students)
save_students(filename, students)
elif choice == "3":
check_balance(students)
elif choice == "4":
print("谢谢使用,再见!")
break
else:
print("输入有误,请重新输入!")
# 运行主函数
if __name__ == "__main__":
main()
```
在主函数中,首先读取student.txt文件的学生信息,然后进入一个循环,根据用户输入的选择执行相应的操作,最后保存学生信息并退出程序。
阅读全文