当用户在jtextfield中输入1和2以外的其他整数时,我试图抛出异常。
public class SearchEmployee extends javax.swing.JFrame {
/**
* Creates new form SearchEmployee
*/
public SearchEmployee() {
initComponents();
}
// A utility function to check
// whether a code is valid or not
public static boolean isCodeValid(String id)
throws IdNotFoundException
{
if(!id.equals("1")){
throw new IdNotFoundException();
}else if(!id.equals("2")){
throw new IdNotFoundException();
}
else{
return true;
}
}据推测,在用户点击搜索按钮后,他们将进入新页面,在该页面中将显示员工的详细信息。
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String id = staffID.getText();
try{
if(isCodeValid("1")){
EmployeeDetails emp = new EmployeeDetails();
emp.name.setText("Sky Peach");
emp.email.setText("skypeach@gmail.com");
emp.address.setText("Pangsapuri Sri Puteri");
emp.phoneNo.setText("1999999999");
emp.department.setText("IT");
emp.designation.setText("Software Developer");
emp.show();
}else if(isCodeValid("2")){
EmployeeDetails emp = new EmployeeDetails();
emp.name.setText("Sky Orange");
emp.email.setText("skyorange@gmail.com");
emp.address.setText("Pangsapuri Sri Puteri");
emp.phoneNo.setText("2999999999");
emp.department.setText("IT");
emp.designation.setText("Software Engineer");
emp.show();
}
}catch (IdNotFoundException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
} 但是,即使当我输入整数1和2时,也会引发异常。如何修复此错误?
发布于 2022-06-10 14:49:22
在注释中对Rogue和DevilsHnd答案进行扩展后,我建议切换用于字符串比较的参数。这避免了id参数为null时的NPEs。
public static boolean isCodeValid(String id) { return "1".equals(id) || "2".equals(id); }或者在此之前进行异常空检查(防御性编程)。使用regex的方法更容易扩展。
public static boolean isCodeValid(String id) {
Objects.requireNonNull(id);
return id.matches("[12]");
}https://stackoverflow.com/questions/72575071
复制相似问题