Pregunta

Hi i am truing to read data from a file and then i want to compare that string from my string i that string is equal to my string then run if condition otherwise else condition

My.jsp

   <%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ page import="java.io.*" %>
<html>
<body>


       <%
           String s1="1";
          // int i=4;
           // String s=null;
          // String s2="1";
           String s3=null;
            String file = application.getRealPath("/") + "data.txt";
           BufferedReader reader = new BufferedReader(new FileReader(file));

            String line;
            while((line = reader.readLine())!= null){

                s3=line.toString();
            }

  if(s3.equalsIgnoreCase(s1))
      %>
     <%@ include file="MarketWiseData.jsp" %>
     <%else
  {%>
      <%@ include file="CommodityWise.jsp" %>
<%
          }
%>

</body>
</html>

How can i get my target ?

Thanks in advance

¿Fue útil?

Solución 2

You will get java.lang.NullPointerException at the line if(line.equalsIgnoreCase(s1)), because in your while loop, you have a check if line != null, and until the line is not null, your loop executing and when the line=null, code exit from loop and your if Condition occurs in which you checked if(line.equalsIgnoreCase(s1)) and since line=null, so you will get NullPointerException at your if condition.

I think you want this :

while((line = reader.readLine())!= null){
if(line.equalsIgnoreCase(s1))
     out.println("Shkati");
  else
  {
  out.println("sharma");
  }
}

Otros consejos

Read your code:

while((line = reader.readLine()) != null) {
    // sb.append(line+"\n");
    out.println(line);
}

if (line.equalsIgnoreCase(s1))
    out.println("Shkati");
else {
    out.println("sharma");
}

You have a while loop that keeps running while line is not null. It thus stops when line is null. So, in the if test, line is guaranteed to be null. And the test is thus guaranteed to throw a NullPointerException, since calling a method on null doesn't make sense.

Note that if, as in my code above, your code was properly indented, you would be able to immediately see its structure and logic. Failing to indent your code makes it confusing and unclear for yourself.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top