I am trying to throw the exception when the user enters other integer than 1 and 2 into the jtextfield,
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;
}
}
and supposedly after users clicked the search button, they are supposedly going to the new page where employee details will be displayed.
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("[email protected]");
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("[email protected]");
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());
}
}
however, the exception was thrown even when i entered the integer 1 and 2. How to fix this error?
Expanding on Rogue and DevilsHnd answer in the comments, I would suggest to switch the arguments used for the string comparison. This avoids NPEs when the id parameter is null.
Or make an excplicit null check (defensive programming) before. The approach with the regex is simpler to expand