Sukanta Pal
Sukanta Pal

Reputation: 33

How could I compare two string in Jsp?

if(student_code.substring(0,3 )=="MLV")
  count1++;

But count1 always return 0

Upvotes: 0

Views: 37830

Answers (3)

Sukanta Pal
Sukanta Pal

Reputation: 33

Oho friends .... I just change my code to

str1=student_code.substring(0,3 ).trim();
if(str1.equals("YML"))
  count1++;

..and its working

Upvotes: 0

Amit.rk3
Amit.rk3

Reputation: 2417

if(student_code.substring(0,3 )=="MLV")
  count1++;

This doesn't look like a JSP code. It looks more of a scriptlet in JSP, which is nothing but java code. If that's the case, you still need to use equals for string comparison, like

if(student_code.substring(0,3 ).equals("MLV"))
      count1++;

If you want to substring and compare strings in JSP, use JSTL functions as shown below

<c:set var="mystring" value="<%=student_code%>"/>

<c:if test="${fn:substring(mystring, 0, 3) == 'MLV'}">
     <%count1++;%>
<c:if>

Also for above JSTL code to work you would need to import below taglibs in JSP

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

Upvotes: 9

Masutatsu
Masutatsu

Reputation: 444

You can use the '==' symbols to compare two strings in JSP, I would put spaces inbetween and change the double quotes to singles, e.g:

if(student_code.substring(0,3 ) == 'MLV')

Hopefully this helps.

Reference post: How to compare two object variables in EL expression language?

Upvotes: 0

Related Questions