编程任务:随机分组小程序。 要求:输入分组总人数,每组人数。然后产生随机分组。有一定的可视化界面。 请用Java语言给出详细代码
时间: 2024-10-28 11:11:58 浏览: 16
为了创建一个随机分组的小程序,我们可以使用Java Swing库来构建一个简单的用户界面,并结合`java.util.Random`类来生成随机分组。以下是简化的代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
public class RandomGroupingApp extends JFrame {
private JLabel inputLabel, groupSizeLabel;
private JTextField totalPeopleField, groupSizeField;
private JButton generateButton;
private JTextArea resultArea;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
RandomGroupingApp window = new RandomGroupingApp();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
public RandomGroupingApp() {
setTitle("Random Group Generator");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Input fields and labels
inputLabel = new JLabel("Total People:");
totalPeopleField = new JTextField(10);
groupSizeLabel = new JLabel("Group Size:");
groupSizeField = new JTextField(10);
// Generate button
generateButton = new JButton("Generate Groups");
generateButton.addActionListener(e -> generateGroups());
// Result area
resultArea = new JTextArea(5, 30);
resultArea.setEditable(false);
// Add components to the frame
add(inputLabel);
add(totalPeopleField);
add(groupSizeLabel);
add(groupSizeField);
add(generateButton);
add(new JScrollPane(resultArea));
}
private void generateGroups() {
int totalPeople = Integer.parseInt(totalPeopleField.getText());
int groupSize = Integer.parseInt(groupSizeField.getText());
ArrayList<String> groups = new ArrayList<>();
for (int i = 0; i < totalPeople / groupSize; i++) {
String group = "Group " + (i + 1);
Collections.shuffle(Arrays.asList("Person" + (i * groupSize + 1), "Person" + (i * groupSize + 2), ...,"Person" + ((i + 1) * groupSize)));
groups.add(group + ": " + Arrays.toString(Arrays.copyOfRange(list, 0, groupSize)));
}
resultArea.setText("Groups:\n" + groups.toString());
}
}
阅读全文