java 成绩_java 学生成绩排序

该博客介绍了一个Java程序,用于记录和排序学生的姓名及成绩。程序创建了一个JFrame窗口,包含输入姓名和成绩的文本框,点击确定按钮后,会将数据存储到Map中并进行排序。排序通过一个名为`sortMapByValue`的方法实现,该方法利用了LinkedHashMap保持插入顺序的特点,并使用Comparator接口根据值(成绩)进行比较。排序后的结果显示在JTextArea中。
摘要由CSDN通过智能技术生成

importjava.awt.BorderLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.util.ArrayList;importjava.util.Collections;importjava.util.Comparator;importjava.util.HashMap;importjava.util.Iterator;importjava.util.LinkedHashMap;importjava.util.List;importjava.util.Map;importjava.util.Map.Entry;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JPanel;importjavax.swing.JTextArea;importjavax.swing.JTextField;public class Student extendsJFrame {

JLabel lName,lScore;

JTextField tName,tScore;

JTextArea taShow;

JButton bSubmit;

JPanel pan;

MapstudentMap,resultMap;public static voidmain(String[] args) {newStudent();

}publicStudent() {

init();

click();

}public voidinit() {

lName=new JLabel("姓名");

lScore=new JLabel("成绩");

tName=new JTextField(10);

tScore=new JTextField(10);

bSubmit=new JButton("确定");

pan=newJPanel();

taShow=newJTextArea();

pan.add(lName);

pan.add(tName);

pan.add(lScore);

pan.add(tScore);

pan.add(bSubmit);

add(pan,BorderLayout.NORTH);

add(taShow, BorderLayout.CENTER);

setTitle("学生成绩排序");

setSize(400, 300);

setVisible(true);

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

validate();

studentMap=new HashMap();

}private voidclick() {

bSubmit.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {

save();

showMap();

}

});

}private voidsave() {

studentMap.put(tName.getText(),tScore.getText());

resultMap=sortMapByValue(studentMap);

tName.setText("");

tScore.setText("");

}public static Map sortMapByValue(Mapmap) {if (map == null ||map.isEmpty()) {return null;

}

Map sortedMap = new LinkedHashMap();

List> entryList = new ArrayList>(map.entrySet());

Collections.sort(entryList,newMapValueComparator());

Iterator> iter =entryList.iterator();

Map.Entry tmpEntry = null;while(iter.hasNext()) {

tmpEntry=iter.next();

sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());

}returnsortedMap;

}private voidshowMap() {

taShow.setText("");for(Map.Entryentry:resultMap.entrySet()) {

taShow.append("姓名:"+entry.getKey()+" 成绩:"+entry.getValue()+"\n");

}

}

}class MapValueComparator implements Comparator>{public int compare(Entry s1, Entrys2) {returns1.getValue().compareTo(s2.getValue());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值