Jeremy Garcia
Jeremy Garcia

Reputation: 1

Logic issue with the if-statement in java-ee

I have a logical issue with the "if". I have to parameter, one textbox and a select. Both are to insert the category but the select is generate from the database and allows the user to select a category quickly. I would like to insert the category of the textbox if this one is not null and the select is empty. If it is the opposite use the select value. If both are select (text in textbox + selection in the select), then choose the select value. In the case of having both empty I will define a default value "Other".

This is the code:

//addRss.jsp

<select name="catOption">
<option value="">select category</option>
<c:forEach var="cat" items="${categories}">
    <option value="${cat}">${cat}</option>
</select>
<label for="category">Category</label>
<input type="text" id="category" name="category" value="" size="20" maxlength="20" />


//AddNewRss

String catText = request.getParameter("category");
    String catOption = request.getParameter("catOption");
    String category = "";

    if((catOption != null || !catOption.trim().isEmpty()) && (catText == null || catText.trim().isEmpty()))
        category = catOption;
    else if((catOption == null || catOption.trim().isEmpty()) && (catText != null || !catText.trim().isEmpty()))
        category = catText;
    else if((catOption != null || !catOption.trim().isEmpty()) && (catText != null || !catText.trim().isEmpty()))
        category = catOption;
    else
        category = "Other";

My problem is that in the case of both empty, the program will do the first "if" and send a empty category.

Do you see something wrong ?

Thank you

Jeremy.

Ps: sorry English is not my main language.

Upvotes: 0

Views: 173

Answers (1)

Majid Laissi
Majid Laissi

Reputation: 19788

if((catOption != null && !catOption.trim().isEmpty()) 
    && (catText == null || catText.trim().isEmpty())) {
        category = catOption;
}
else if((catOption == null || catOption.trim().isEmpty())
    && (catText != null && !catText.trim().isEmpty())) {
        category = catText;
}
else if((catOption != null && !catOption.trim().isEmpty())  {
    && (catText != null && !catText.trim().isEmpty()))
        category = catOption;
}
else {
    category = "Other";
}

You can also make things more readable by creating a function:

private boolean isNullOrEmty(String str) {
     return str == null || str.trim().isEmpty();
}


if( ! isNullOrEmty(catOption) && isNullOrEmty(catText) ) {
        category = catOption;
}
else if( isNullOrEmty(catOption) && ! isNullOrEmty(catText)) {
        category = catText;
}
else if(!isNullOrEmty(catOption) && ! isNullOrEmty(catText))
        category = catOption;
}
else {
    category = "Other";
}

Upvotes: 1

Related Questions