<%@ page import="java.util.*,MagicSquareFactory,MagicSquare,OddOrderMagicSquare,SinglyEvenOrderMagicSquare,DoublyEvenOrderMagicSquare" %> <%// process page
String action = request.getParameter("action"); String nString = request.getParameter("n"); String aString = request.getParameter("a");
int n = -1;
int a = -1000;boolean hasError = false;
String message = null;if (action == null || action.equals("Clear")) {
nString = null; aString = null;}
else if (nString == null || nString.equals("")) {hasError = true; message = "Enter an integer >= 3 for <i>n</i>!";}
else if (aString == null || aString.equals("")) {hasError = true; message = "Enter an integer for <i>a</i>!";}
else
{try { n = Integer.valueOf(nString).intValue(); } catch (NumberFormatException nfe) { hasError = true; message = "Enter an integer >= 3 for <i>n</i>!"; } try { a = Integer.valueOf(aString).intValue(); } catch (NumberFormatException nfe) { hasError = true; message = "Enter an integer for <i>a</i>!"; } if (!hasError) { if (action.equals("Display")) { if (n < 3) { hasError = true; message = "Enter an integer >= 3 for <i>n</i>!"; } } }}
// print page
%>
<html>
<head><title>Magic Square</title></head> <body bgcolor="white">
<font size=3>
A <i>Magic Square</i> of order <i>n</i> with start value <i>a</i> is an <i>n</i> by <i>n</i> matrix of consecutive integers starting from <i>a</i>, where each row sum, column sum and diagonal sum of <i>n</i> integers is the same. <p>
Enter integers <i>n</i> >= 3 and <i>a</i> below to display a magic square of order <i>n</i> with start value <i>a</i>. <p>
<form method=POST action=MagicSquare.jsp> <%if (nString == null || nString.equals("")) {
%>
<i>n</i> <input text=text name=n size=2 maxlength=2> <%}
else
{
%>
<i>n</i> <input text=text name=n value=<%= nString %> size=2 maxlength=2> <%}
%>
<br>
<%if (aString == null || aString.equals("")) {
%>
<i>a</i> <input type=text name=a size=4 maxlength=4> <%}
else
{
%>
<i>a</i> <input type=text name=a value=<%= aString %> size=4 maxlength=4> <%}
%>
<p>
<i>
<input type=submit name=action value="Display"> <input type=submit name=action value="Clear"> </i>
</form>
<p>
<%if (action == null || action.equals("Clear")) {
}
else if (hasError)
{
%>
<%= message %>
<%}
else if (action.equals("Display"))
{MagicSquare magicSquare = MagicSquareFactory.create(a, n); %>
<table border=1>
<%for (int row=0; row<n; row++) {%>
<tr>
<%for (int col=0; col<n; col++) {%>
<td align=center><%= magicSquare.getCell(row, col) %> <%} }%>
</table>
<%}
%>
</font>
<hr>
<a href="http://www.computing-wisdom.com"><i>Computing Wisdom Inc. Home Page</i></a> </body>
</html>