Java编程大赛题目科普
1. 引言
Java编程大赛是一个面向全国中小学生的Java编程比赛,旨在提高学生的编程能力和创新思维。本文将介绍一道典型的Java编程大赛题目,并以代码示例的形式详细解答。
2. 题目描述
题目要求实现一个简单的学生成绩管理系统,包含以下功能:
- 添加学生信息
- 删除学生信息
- 修改学生信息
- 查询学生信息
- 计算学生平均分
- 统计不及格人数
3. 解题思路
为了实现上述功能,我们可以使用面向对象的思想,设计以下几个类:
- 学生类(Student):用于存储学生的基本信息,如姓名、学号、成绩等。
- 学生管理类(StudentManager):用于实现学生信息的增删改查功能,以及计算平均分和统计不及格人数功能。
- 主程序类(Main):用于测试学生管理系统。
4. 代码示例
下面是具体的代码实现:
4.1 学生类(Student)
public class Student {
private String name;
private int id;
private double score;
public Student(String name, int id, double score) {
this.name = name;
this.id = id;
this.score = score;
}
// 省略getter和setter方法
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", score=" + score +
'}';
}
}
4.2 学生管理类(StudentManager)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StudentManager {
private List<Student> students;
public StudentManager() {
students = new ArrayList<>();
}
public void addStudent(Student student) {
students.add(student);
}
public void removeStudent(int id) {
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
if (student.getId() == id) {
iterator.remove();
break;
}
}
}
public void updateStudent(int id, Student newStudent) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() == id) {
students.set(i, newStudent);
break;
}
}
}
public Student findStudent(int id) {
for (Student student : students) {
if (student.getId() == id) {
return student;
}
}
return null;
}
public double calculateAverageScore() {
double sum = 0;
for (Student student : students) {
sum += student.getScore();
}
return sum / students.size();
}
public int countFailedStudents() {
int count = 0;
for (Student student : students) {
if (student.getScore() < 60) {
count++;
}
}
return count;
}
public void printAllStudents() {
for (Student student : students) {
System.out.println(student);
}
}
}
4.3 主程序类(Main)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StudentManager studentManager = new StudentManager();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1. 添加学生信息");
System.out.println("2. 删除学生信息");
System.out.println("3. 修改学生信息");
System.out.println("4. 查询学生信息");
System.out.println("5. 计算学生平均分");
System.out.println("6. 统计不及格人数");
System.out.println("0. 退出程序");
System.out.print("请输入功能编号:");
int choice = scanner.nextInt();
if (choice == 0) {
break;
}
switch (choice) {
case 1:
System.out.print("请输入学生姓名:");
String name = scanner.next();
System.out.print("请输入学生学号:");
int id = scanner.nextInt();
System.out.print("请输入学生成绩:");
double score = scanner.nextDouble();
Student student = new Student(name, id, score);
studentManager.addStudent(student);
System.out.println("学生信息添加成功!");
break;
case 2:
System.out.print("请输入要删除的学生学号