Monday, 3 December 2012

Declaring Methods (Method to calculate percentages)

                A method stores a group of Java statements that you can execute from more than one location in your JSP page.This saves you from repeating the same code and allows you to update the code in a central location.You can call a methods as many times as you like.
         
              A method can accept arguments and return a result to the code from which it was called, providing greater flexibility.

Simple JSP Program Using Methods:


<html>
<head>
<title> Simple JSP page </title>
</head>
<body>
<h3>Method to calculate Percentage </h3>
<p>
<%!
float calculatePercentage(float a,float b)
{
 float result=a/b * 100;
 return result;
}
%>
<p>
Percentage of (15/20) is <%=calculatePercentage(15,20) %>%
<br>
Percentage of (10/20) is <%=calculatePercentage(10,20)%>%
<br>
Percentage of (5/20) is <%=calculatePercentage(5,20) %>%
<br>
</body>
</html>

Description:

  • Type <%! to open the declaration tag.
  • Type the keyword for the type of data that the method will return.(In the above example. "float" is used).If you type void the method will not return a value.
  • Type the name of the method(calculatePercentage)
  • Type opening and closing parentheses after the method name.({ and })
  • Declare the arguments that the method can accept.(float a, float b).A method can accept multiple arguments.
  • Insert the reusable code within braces.
             float result=a/b * 100;
             return result;
  • Type the keyword return  before the value or variable to be passed back to the calling method code.
              return result;
  • Type %> to close the declaration tag.
  • Use the Expression tag to print the result returned by the method.
  • Type the method name between the expression tag delimiters.
             calculatePercentage
  • Pass the Parameters to the method in the order that they were declared.
             <%=calculatePercentage(15,20) %>


********************************OUTPUT****************************************

Method to calculate Percentage

Percentage of (15/20) is 75.0%
Percentage of (10/20) is 50.0%
Percentage of (5/20) is 25.0% 


********************************************************************************

No comments:

Post a Comment