Search code examples
javaif-statementequalsjtextfieldgettext

Get the text from the field but if blank do this


I have a number of fields where data needs to be input. This is a Hotel Reservation system so if the fields arent filled it must display that they are empty and cannot proceed without filling them. What I want to do is get the text from the fields but if they are blank it must either set all the fields text to something like "*Please fill in all fields" or show up a message. I have some code which is not working because it cant get the text if there's nothing in the fields. The code looks like this:

    this.Firstname = NameF.getText();
        this.Lastname = NameL.getText();
        this.Country = Countr.getText();
        this.IDtype = IDTy.getText();
        this.PassportNo = PassNo.getText();
        this.IDNo = IDNumber.getText();
        this.Addr1 = Add1.getText();
        this.Addr2 = Add2.getText();
        this.AreaCode = Integer.parseInt(Area.getText());
        this.TelNo = Tel.getText();
        this.CellNo = Cell.getText();
        this.Email = Em.getText();
    }
    if (this.Firstname.equals("") || this.Lastname.equals("") || this.Country.equals("") || this.IDtype.equals("") || this.IDNo.equals("") || this.Addr1.equals("") || this.Addr2.equals("") || this.AreaCode == 0 || this.TelNo.equals("") || this.CellNo.equals("") || this.Email.equals("")) {
        JOptionPane.showMessageDialog(null, "Please fill in all fields");
    }

Not sure if I should ask this in another question but is there an easier way to make the if without so many || operators? Just like if this.Firstname,this.Lastname,etc.equals("")


Solution

  • You could do this by creating a function to do the checks for you in a loop;

    public boolean isAnyEmpty(String... strArr){
        for(String s : strArr){
            if(s.equals("")) return true;
        }
        return false; 
    }
    

    Then call it with

    if(isAnyEmpty(this.Firstname, this.lastName, this.Country, /* rest of your strings */)){
        //your code
    }
    

    This method makes use of varargs to let you treat the parameters as an array, without having to add in the additional code to explicitly create one.