全部。我正在编写一个 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;
}
}
});
这是我处理按钮 Action 监听器的代码。在插入情况下,我想创建此支票。谢谢!
最佳答案
java.util.HashMap 提供了一个内置功能来检查 key 是否存在。
您可以通过以下方式获取支票:
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/