编写一个java程序随机点名和程序,使其能够在全班同学中随机点中某一名同学的名字。 随机点名器具备3个功能, (1)存储全班同学的姓名(2)总览全班同学姓名(3)随机点取其中一人姓名
时间: 2024-06-12 16:05:55 浏览: 75
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class RandomNamePicker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> students = new ArrayList<String>();
Random randomGenerator = new Random();
while (true) {
System.out.println("请选择功能:");
System.out.println("1. 存储全班同学的姓名");
System.out.println("2. 总览全班同学姓名");
System.out.println("3. 随机点取其中一人姓名");
int option = scanner.nextInt();
switch (option) {
case 1:
System.out.println("请输入学生姓名,输入0结束:");
while (true) {
String name = scanner.next();
if (name.equals("0")) {
break;
}
students.add(name);
}
break;
case 2:
System.out.println("全班学生名单如下:");
for (String name : students) {
System.out.println(name);
}
break;
case 3:
if (students.isEmpty()) {
System.out.println("请先存储全班同学的姓名!");
break;
}
int index = randomGenerator.nextInt(students.size());
String randomName = students.get(index);
System.out.println("被选中的同学是:" + randomName);
break;
default:
System.out.println("无效的选项,请重新选择!");
break;
}
}
}
}
阅读全文