将二十个人按五人一组分组并使用student类编写Java程序
时间: 2024-05-11 09:16:22 浏览: 78
JAVA程序编写要点-java程序编写要点
好的,让我理解一下你的问题。您需要编写一个Java程序,将二十个人分成五组,每组包含五个人,并使用student类编写。是吗?
如果是的话,以下是这样一个Java程序的示例代码:
```java
public class Student {
private String name;
private int age;
private String group;
public Student(String name, int age, String group) {
this.name = name;
this.age = age;
this.group = group;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
public class Grouping {
public static void main(String[] args) {
Student[] students = new Student[20];
students[0] = new Student("John", 20, "");
students[1] = new Student("Mary", 19, "");
students[2] = new Student("David", 21, "");
students[3] = new Student("Alice", 18, "");
students[4] = new Student("Bob", 22, "");
students[5] = new Student("Jack", 20, "");
students[6] = new Student("Lucy", 19, "");
students[7] = new Student("Peter", 21, "");
students[8] = new Student("Sara", 18, "");
students[9] = new Student("Tom", 22, "");
students[10] = new Student("Eva", 20, "");
students[11] = new Student("Mike", 19, "");
students[12] = new Student("Maggie", 21, "");
students[13] = new Student("Jim", 18, "");
students[14] = new Student("Linda", 22, "");
students[15] = new Student("Tim", 20, "");
students[16] = new Student("Kate", 19, "");
students[17] = new Student("Frank", 21, "");
students[18] = new Student("Cathy", 18, "");
students[19] = new Student("Joe", 22, "");
Random random = new Random();
List<Integer> list = new ArrayList<>(20);
for (int i = 0; i < 20; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < 5; i++) {
System.out.println("Group " + (i + 1));
for (int j = 0; j < 5; j++) {
int index = list.get(i * 5 + j);
students[index].setGroup("Group " + (i + 1));
System.out.println(students[index].getName());
}
System.out.println();
}
}
}
```
在这个程序中,我们首先定义了一个student类来表示每个学生。然后,我们创建了一个包含20个学生的数组,并将每个学生的信息填充到数组中。
接下来,我们使用一个Random对象,将0到19的整数放入一个ArrayList中。然后,使用Collections.shuffle()方法打乱ArrayList中的元素,保证每次执行程序时,分组都是随机的。
最后,我们使用两个嵌套的for循环,将20个学生分为5组,并打印出每个组中的学生名称。
希望这个程序能够对您有所帮助!
阅读全文