else if (e.getSource().equals(login)) { String id=jt1.getText(); String username = jt2.getText(); String password = String.valueOf(jpf.getPassword()); // 遍历所有学生信息,判断输入的用户名和密码是否匹配 boolean isMatched = false; for (Student student : students) { if (username.equals(student.getUserName()) && password.equals(String.valueOf(student.getPassword()))&&id.equals(student.getId())) { isMatched = true; break; } }修改代码
时间: 2024-02-15 07:08:47 浏览: 115
在对所有学生信息进行遍历之前,您可以先进行一些输入验证,比如判断输入框是否为空。另外,您可以把判断逻辑封装成一个方法,以提高代码可读性和复用性。修改后的代码如下所示:
```
else if (e.getSource().equals(login)) {
String id = jt1.getText();
String username = jt2.getText();
String password = String.valueOf(jpf.getPassword());
// 输入验证
if (id.isEmpty() || username.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入完整信息!", "提示", JOptionPane.WARNING_MESSAGE);
return;
}
// 判断用户名、密码和ID是否匹配
boolean isMatched = isStudentMatched(id, username, password);
if (isMatched) {
JOptionPane.showMessageDialog(this, "登录成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "用户名、密码或ID错误!", "提示", JOptionPane.WARNING_MESSAGE);
}
}
// 判断学生信息是否匹配
private boolean isStudentMatched(String id, String username, String password) {
for (Student student : students) {
if (id.equals(student.getId()) && username.equals(student.getUserName()) && password.equals(String.valueOf(student.getPassword()))) {
return true;
}
}
return false;
}
```
阅读全文