0

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.

4

1 回答 1

1
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";
}

您还可以通过创建一个函数使内容更具可读性:

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";
}
于 2013-06-11T17:42:42.360 回答