I have a simple JFrame with three text boxes: First Name, Last Name and E-Mail address. Once the add button is pressed, the details are added to an Array List. Currently I have a group of if statements to check if the user has entered something in the text box as shown below:
private void addPersonButtonActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = firstNameTextField.getText();
String lastName = lastNameTextField.getText();
String emailAddress = emailTextField.getText();
if (firstName.equals("")) {
System.out.println("First Name is missing");
} else if (lastName.equals("")) {
System.out.println("Last Name is missing");
} else if (emailAddress.equals("")) {
System.out.println("E-Mail address is missing");
} else if (!Email.isValid(emailAddress)) {
System.out.println("E-Mail address is invalid");
} else {
personArrayList.add(new Person(firstName, lastName, emailAddress));
System.out.println("Person added!");
}
}
However, I find having long blocks of if statements makes the code difficult to read; it also won't alert the user about multiple text fields being empty. Is there a more efficient way of doing this?
Thanks in advance!
"".equals(yourstring)instead ofyourstring.equals(""), it will allow not to throw an NPE ifyourstringappends to be null for one reason or anothergetText()suddenly starts returning null, it's probably a good idea to get a nice exception about that.