java编程,java 弹出窗口输入多个分数,用逗号隔开,通过单选框选择是从小到大排列还是从大到小排列,输出排列结果
时间: 2024-02-28 20:54:37 浏览: 94
java代码-输入3个数,按从小到大输出。
好的,针对您的问题,我可以给您一个简单的 Java 代码示例,如下所示:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
public class ScoreSorter extends JFrame implements ActionListener {
JTextField scoreField;
JRadioButton ascBtn, descBtn;
JButton sortBtn;
public ScoreSorter() {
initUI();
}
private void initUI() {
setTitle("Score Sorter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 1));
JPanel scorePanel = new JPanel();
JLabel scoreLabel = new JLabel("Scores:");
scoreField = new JTextField(20);
scorePanel.add(scoreLabel);
scorePanel.add(scoreField);
JPanel orderPanel = new JPanel();
JLabel orderLabel = new JLabel("Order:");
ascBtn = new JRadioButton("Ascending");
descBtn = new JRadioButton("Descending");
ButtonGroup group = new ButtonGroup();
group.add(ascBtn);
group.add(descBtn);
orderPanel.add(orderLabel);
orderPanel.add(ascBtn);
orderPanel.add(descBtn);
JPanel buttonPanel = new JPanel();
sortBtn = new JButton("Sort");
sortBtn.addActionListener(this);
buttonPanel.add(sortBtn);
panel.add(scorePanel);
panel.add(orderPanel);
panel.add(buttonPanel);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
new ScoreSorter();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sortBtn) {
String[] scores = scoreField.getText().split(",");
int[] intScores = new int[scores.length];
for (int i = 0; i < scores.length; i++) {
intScores[i] = Integer.parseInt(scores[i].trim());
}
if (ascBtn.isSelected()) {
Arrays.sort(intScores);
} else {
Arrays.sort(intScores);
for (int i = 0; i < intScores.length / 2; i++) {
int temp = intScores[i];
intScores[i] = intScores[intScores.length - 1 - i];
intScores[intScores.length - 1 - i] = temp;
}
}
JOptionPane.showMessageDialog(this, Arrays.toString(intScores));
}
}
}
```
这个程序使用了 Swing 组件来构建 GUI,可以通过文本框输入多个分数,然后通过单选按钮选择是从小到大排列还是从大到小排列,最后点击按钮可以输出排列结果。在程序中,我们使用了 `Arrays.sort()` 方法来排序,如果选择了从大到小排列,那么我们还需要交换数组中的元素来实现排序。
阅读全文