2013-06-11 2 views
0

"if"에 논리적 인 문제가 있습니다. 하나의 텍스트 상자와 선택 항목을 매개 변수로 사용해야합니다. 둘 다 범주를 삽입하지만 선택은 데이터베이스에서 생성되므로 사용자가 범주를 신속하게 선택할 수 있습니다. 이 하나가 null이 아니고 select가 비어있는 경우 텍스트 상자의 범주를 삽입하고 싶습니다. 반대라면 선택 값을 사용하십시오. 둘 다 선택하면 (텍스트 상자의 텍스트 + 선택 항목) 선택 값을 선택하십시오. 둘 다 비어있는 경우 기본값 인 "기타"를 정의합니다. java-ee의 if 문에 대한 논리 문제

코드입니다 :

//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"; 

내 문제는 모두 빈의 경우, 프로그램이 처음 "경우"를 수행하고 빈 카테고리를 보낼 것입니다.

잘못된 것이 있습니까?

고맙습니다.

제레미.

Ps : 죄송합니다. 영어가 제 주요 언어가 아닙니다.

+0

'경우 ((catOption = NULL ||'->'경우 ((catOption를 = 널 (null) &&' – Maroun

+0

을 catOption! = null ||! catOption.trim(). isEmpty()'catOption이 실제로 null 인 경우 감지하지 못합니다. NullPointerException이 발생합니다. –

답변

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"; 
} 
+0

감사합니다! :) –

+0

' 다시 환영 :) –