java用单链表写一个简单的学生系统
时间: 2023-10-29 18:04:17 浏览: 128
单链表实现的学生信息系统
好的,以下是一个简单的Java代码示例,用单链表实现学生系统:
```
import java.util.Scanner;
class Student {
int id;
String name;
int score;
public Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public String toString() {
return "Student ID: " + id + ", Name: " + name + ", Score: " + score;
}
}
class Node {
Student student;
Node next;
public Node(Student student) {
this.student = student;
this.next = null;
}
}
class StudentList {
Node head;
public StudentList() {
head = null;
}
public void addStudent(Student student) {
Node newNode = new Node(student);
if (head == null) {
head = newNode;
} else {
Node currentNode = head;
while (currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
}
public void displayStudents() {
Node currentNode = head;
while (currentNode != null) {
System.out.println(currentNode.student);
currentNode = currentNode.next;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StudentList studentList = new StudentList();
int choice = 0;
while (true) {
System.out.println("\nPlease select an option:");
System.out.println("1. Add a student");
System.out.println("2. Display all students");
System.out.println("3. Exit");
choice = scanner.nextInt();
if (choice == 1) {
System.out.println("\nEnter student ID:");
int id = scanner.nextInt();
System.out.println("Enter student name:");
String name = scanner.next();
System.out.println("Enter student score:");
int score = scanner.nextInt();
Student student = new Student(id, name, score);
studentList.addStudent(student);
System.out.println("\nStudent added successfully!");
} else if (choice == 2) {
System.out.println("\nStudent List:");
studentList.displayStudents();
} else if (choice == 3) {
System.out.println("\nExiting...");
break;
} else {
System.out.println("\nInvalid choice!");
}
}
scanner.close();
}
}
```
这个程序使用了单链表来存储学生对象,实现了添加学生和显示所有学生的功能。当用户选择添加学生时,程序会要求用户输入学生的ID、姓名和成绩,然后将学生添加到单链表中。当用户选择显示所有学生时,程序会遍历单链表并打印每个学生的信息。用户可以通过选择“退出”选项来结束程序的运行。
阅读全文