java随机点名,显示学生姓名、学号、年龄的代码
时间: 2023-06-08 15:08:19 浏览: 159
基于java的学生随机点名系统
5星 · 资源好评率100%
以下是一个简单的Java代码示例,用于随机点名并显示学生的姓名、学号和年龄:
```
import java.util.ArrayList;
import java.util.Random;
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 class RandomNamePicker {
private ArrayList<Student> students;
public RandomNamePicker(ArrayList<Student> students) {
this.students = students;
}
public Student pickRandomName() {
Random random = new Random();
return students.get(random.nextInt(students.size()));
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Alice", 1001, 20));
students.add(new Student("Bob", 1002, 21));
students.add(new Student("Charlie", 1003, 19));
RandomNamePicker picker = new RandomNamePicker(students);
Student randomStudent = picker.pickRandomName();
System.out.println("Name: " + randomStudent.getName());
System.out.println("ID: " + randomStudent.getId());
System.out.println("Age: " + randomStudent.getAge());
}
}
```
这个例子中,我们定义了一个Student类,它有三个属性:name,id和age。然后,在RandomNamePicker类中,我们创建了一个ArrayList来存储学生信息,并定义了一个方法pickRandomName(),该方法使用Random类从学生列表中随机选择一个学生。最后,在main()方法中,我们创建了一个RandomNamePicker对象,并使用它从学生列表中随机选择一个学生。然后,我们打印出选中学生的姓名、学号和年龄。
阅读全文