所有。我正在编写一个GUI程序,该程序允许用户输入学生ID,姓名和专业。他们可以将这些值作为记录插入到学生数据库中,将其删除,查找或更新。我想做的是创建一个检查(也许是if语句),以防止用户插入Hashmap中已经存在的ID。
processButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae){
int idKey = Integer.parseInt(idText.getText());
String nameValue = nameText.getText();
String majorValue = majorText.getText();
String s = (String)comboList.getSelectedItem();
switch(s) {
case "Insert":
hmap.put(idKey, nameValue);
JOptionPane.showMessageDialog(null, "Student added.");
idText.setText("");
nameText.setText("");
majorText.setText("");
break;
case "Delete":
hmap.remove(idKey);
JOptionPane.showMessageDialog(null, "Student removed.");
idText.setText("");
nameText.setText("");
majorText.setText("");
break;
case "Find":
String var = hmap.get(idKey);
JOptionPane.showMessageDialog(null, "Student found."
+ "\n" + var);
idText.setText("");
nameText.setText("");
majorText.setText("");
break;
case "Update":
JFrame frame = new JFrame();
Object[] grades = {"A", "B", "C", "D", "F"};
String gradeAdded = (String)JOptionPane.showInputDialog(frame, "Choose grade:",
"", JOptionPane.QUESTION_MESSAGE, null, grades, grades[0]);
Object[] credits = {"3", "6"};
String creditsAdded = (String)JOptionPane.showInputDialog(frame, "Choose credits:",
"", JOptionPane.QUESTION_MESSAGE, null, credits, credits[0]);
idText.setText("");
nameText.setText("");
majorText.setText("");
break;
}
}
});
这是我用于处理按钮actionlistener的代码。在插入的情况下,我想创建此检查。谢谢!
最佳答案
java.util.HashMap提供了一种内置功能来检查密钥是否存在。
您可以进行如下检查:
if (hmap.containsKey(id)) {
...
}
查看以下相同的Java文档:
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#containsKey(java.lang.Object)
关于java - 如何创建检查以防止用户添加现有值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35819276/