jspservletsjsp-tagsservlet-3.0

Cannot be resolved to a variable, expression tag is giving me an error


I'm writing JSP Code for the first time. when I'm declaring an expression statement it's giving me an error;

sum cannot be resolved to a variable.

Here's my code for your reference:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.Date,java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%! 
        public int factorial(int n){
            int ans=1;
            for(int i=1; i<=n; i++){
                ans=ans*i;
            }
            return ans;
    }
    %>
    
    <%@include file="header.html" %>
    <%
        String op = request.getParameter("btn");
        int n1 = Integer.parseInt(request.getParameter("num1"));
        int n2 = Integer.parseInt(request.getParameter("num2"));
        if(op.equals("add")){
            int sum=n1+n2;
        }else{
               
               int sum=factorial(n1);
           }
        
         Date dt=new Date();
           out.println("testing jsp");
    %>
    
    <h2> Addition is: <%=sum %> </h2>
    
    
    <h4>Today's Date : <%=dt %></h4>
    <%@include file="footer.html" %>
</body>
</html>

Error is in Addition = sum line.


Solution

  • You print the variable where it is not available. You can place the output of a variable right after calculation where the variable is yet exists. Don't define a local variable in the blocked code, if you use it outside a block or statement.

    <%
            String op = request.getParameter("btn");
            int n1 = Integer.parseInt(request.getParameter("num1"));
            int n2 = Integer.parseInt(request.getParameter("num2"));
            if(op.equals("add")){
                int sum=n1+n2;%>
    <h2> Addition is: <%=sum %> </h2>