I am assigned to prompt a user to give the order of a magic square (a magic square of order 3 would be a 3x3 matrix) and then generate a magic square of that order without using a 2 dimensional array.
Here's what I know and understand:
- The Array will have order squared elements.
- When you print out the table, the location of number in the array is [order × row + col]
- The index of the array's location on the table is (index/order, index % order)
Here's what I am given but don't understand how to implement properly:
- row = order − 1, col = order/2 and i = 1
Repeat the following until i = order^2 + 1:
(a) magic[index] = i
(b) increment row and col by 1. that is, row = (row + 1) mod order and col = (col + 1) % order
(c) If magic[index] != 0
i. row = (row + order − 2) % order ii. col = (col + order − 1) % order
(d) increment i by 1
This is my code so far:
package magicsquarecreator;
import java.io.IOException;
import java.util.Scanner;
public class MagicSquareDemo
{
public static void main(String[] args)
{
Scanner keyIn = new Scanner(System.in);
String option;
do
{
System.out.println();
System.out.println(" MAGIC SQUARE APPLICATION ");
System.out.println("==================================================");
System.out.println("Generate a Magic Square........................[1]");
System.out.println("Test for a Magic Square........................[2]");
System.out.println("Quit the Program...............................[0]");
System.out.println();
System.out.print("Select an option -> ");
option = keyIn.next();
System.out.println();
switch(option)
{
case "1":
try
{
System.out.println("Enter the dimension of the magic square -> ");
int order = keyIn.nextInt();
if (order < 1)
{
System.out.println("The order must be positive and odd");
}
else if (order % 2 == 0)
{
System.out.println("The program can only generate a magic square"
+ "\nwhose dimension is positive odd number.");
}
else if (order % 2 != 0)
{
int i=1, j=1;
int row = order - 1;
int col = order/2;
int[] magic = new int[order*order];
for (i=1; i<=order; i++)
{
magic[i] = i;
row = (row + 1) % order;
col = (col + 1) % order;
if (magic[i] != 0)
{
row = (row + order − 2) % order;
col = (col + order − 1) % order;
}
}
}
}
catch(IOException e)
{
System.out.println(e);
}
break;
case "2":
try
{
}
catch(IOException e)
{
System.out.println(e);
}
break;
case "0":
break;
default: System.out.println("Invalid choice...please select a valid menu option.");
}
}
while (option.compareTo("0") != 0);
}
}
Right now I am just worried about getting and understanding case 1. The Try Catch statements for file output, but I can do that on my own time. The biggest problem currently is understanding how to create this loop.