我对“如果”有一个逻辑上的问题。我必须参数,一个文本框和一个select。两者都是插入类别,但select是从数据库生成的,允许用户快速选择类别。如果这个文本框不为空并且选择为空,我想插入文本框的类别。如果恰好相反,则使用选择值。如果两者都是select (文本框中的文本+ select中的选择),则选择选择值。在两者都为空的情况下,我将定义一个默认值"Other“。
代码如下:
//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";我的问题是,在两者都为空的情况下,程序将执行第一个"if“并发送一个空类别。
你有没有发现什么不对劲?
谢谢
杰里米。
注:对不起,英语不是我的主要语言。
发布于 2013-06-12 01:42:42
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";
}https://stackoverflow.com/questions/17050296
复制相似问题