Java/JSP/Method
Содержание
Creating a Method
<HTML>
<HEAD>
<TITLE>Creating a Method</TITLE>
</HEAD>
<BODY>
<H1>Creating a Method</H1>
<%!
int addem(int op1, int op2)
{
return op1 + op2;
}
%>
<%
out.println("2 + 2 = " + addem(2, 2));
%>
</BODY>
</HTML>
Declaring Multiple Methods
<HTML>
<HEAD>
<TITLE>Declaring Multiple Methods</TITLE>
</HEAD>
<BODY>
<H1>Declaring Multiple Methods</H1>
<%!
int addem(int op1, int op2)
{
return op1 + op2;
}
int subtractem(int op1, int op2)
{
return op1 - op2;
}
%>
<%
out.println("2 + 2 = " + addem(2, 2) + "<BR>");
out.println("8 - 2 = " + subtractem(8, 2) + "<BR>");
%>
</BODY>
</HTML>
Define function
<%--
Copyright (c) 2002 by Phil Hanna
All rights reserved.
You may study, use, modify, and distribute this
software for any purpose provided that this
copyright notice appears in all copies.
This software is provided without warranty
either expressed or implied.
--%>
<%!
public int sum(int a, int b)
{
return a + b;
}
%>
2 + 2 = <%= sum(2, 2) %>
Passing Arrays to Methods
<HTML>
<HEAD>
<TITLE>Passing Arrays to Methods</TITLE>
</HEAD>
<BODY>
<H1>Passing Arrays to Methods</H1>
<%!
void doubler(int a)
{
for (int i = 0; i < a.length;i++) {
a[ i ] *= 2;
}
}
%>
<%
int array[] = {1, 2, 3, 4, 5};
out.println("Before the call to doubler...<BR>");
for (int i = 0; i < array.length; i++) {
out.println("array[" + i + "] = " + array[i] + "<BR>");
}
doubler(array);
out.println("After the call to doubler...<BR>");
for (int i = 0; i < array.length; i++) {
out.println("array[" + i + "] = " +
array[i] + "<BR>");
}
%>
</BODY>
</HTML>
Passing the out Object to a Method
<HTML>
<HEAD>
<TITLE>Passing the out Object to a Method</TITLE>
</HEAD>
<BODY>
<H1>Passing the out Object to a Method</H1>
<%!
void printem(javax.servlet.jsp.JspWriter out) throws java.io.IOException
{
out.println("Hello from JSP!");
}
%>
<%
printem(out);
%>
</BODY>
</HTML>
Using Recursion
<HTML>
<HEAD>
<TITLE>Using Recursion</TITLE>
</HEAD>
<BODY>
<H1>Using Recursion</H1>
<%!
int factorial(int n)
{
if (n == 1) {
return n;
}
else {
return n * factorial(n - 1);
}
}
%>
<%
out.println("The factorial of 6 is " + factorial(6));
%>
</BODY>
</HTML>