java在有集合学生管理系统中加入随机点名
时间: 2023-06-20 12:05:23 浏览: 100
要实现随机点名,可以先将学生的姓名存储在一个集合中,然后使用随机数生成器来随机选择一个学生进行点名。
下面是一个示例代码:
```java
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class StudentManager {
private ArrayList<String> students = new ArrayList<String>();
public void addStudent(String name) {
students.add(name);
}
public void removeStudent(String name) {
students.remove(name);
}
public void randomCall() {
if (students.isEmpty()) {
System.out.println("No student available.");
return;
}
Random rand = new Random();
int index = rand.nextInt(students.size());
String name = students.get(index);
System.out.println("Calling: " + name);
}
public static void main(String[] args) {
StudentManager manager = new StudentManager();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Commands: add, remove, call, exit");
System.out.print("> ");
String command = scanner.nextLine();
if (command.equals("add")) {
System.out.print("Enter student name: ");
String name = scanner.nextLine();
manager.addStudent(name);
} else if (command.equals("remove")) {
System.out.print("Enter student name: ");
String name = scanner.nextLine();
manager.removeStudent(name);
} else if (command.equals("call")) {
manager.randomCall();
} else if (command.equals("exit")) {
break;
} else {
System.out.println("Invalid command.");
}
}
}
}
```
这个示例代码中,我们使用了一个ArrayList来存储学生姓名,然后在randomCall方法中使用了Random类来生成一个随机数,然后根据随机数来选择一个学生进行点名。在主函数中,我们使用了一个无限循环来等待用户输入命令,支持添加、删除、点名和退出四种命令。
阅读全文
相关推荐
















