java使用Random和Scanner实现随机点名,存储学生信息(姓名、学号、年龄),总览同学信息,随机产生一个数,查找该随机数所对应的同学信息的代码
时间: 2023-06-08 10:07:49 浏览: 97
好的,以下是Java程序的实现:
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Student {
private String name;
private int id;
private int age;
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public int getAge() {
return age;
}
public String toString() {
return "Name: " + name + ", ID: " + id + ", Age: " + age;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
Scanner scanner = new Scanner(System.in);
Random rand = new Random();
boolean quit = false;
while (!quit) {
System.out.println("What would you like to do?");
System.out.println("1. Add a student");
System.out.println("2. List all students");
System.out.println("3. Randomly select a student");
System.out.println("4. Quit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter student name: ");
String name = scanner.next();
System.out.print("Enter student ID: ");
int id = scanner.nextInt();
System.out.print("Enter student age: ");
int age = scanner.nextInt();
students.add(new Student(name, id, age));
break;
case 2:
for (Student student : students) {
System.out.println(student);
}
break;
case 3:
if (students.isEmpty()) {
System.out.println("There are no students");
break;
}
int index = rand.nextInt(students.size());
Student selected = students.get(index);
System.out.println("Selected student: " + selected);
break;
case 4:
quit = true;
break;
default:
System.out.println("Invalid choice");
}
}
}
}
以上代码实现了简单的学生信息管理系统,包括添加学生信息、总览学生信息、随机选择学生信息等功能。
阅读全文