Write a program which will serve as a Magic Square Tester. In particular, your p
ID: 3626817 • Letter: W
Question
Write a program which will serve as a Magic Square Tester. In particular, your program is to:1. Read data sets of the following form:
a. N, an integer representing the dimension of the array to be tested (maximum 5)
b. The N*N elements of the array, in row order (first row values, then second row values, etc.)
2. Print the N*N values of the array (matrix) in a two-dimensional format.
3. Print the result of performing the test for both criteria as follows:
a. If both criteria are met, print the message Magic Square! below the matrix values.
b. If either condition is not met (or both are not met), print the message Not a Magic Square! below the matrix and also print the criteria that were not met (Sequence criteria failed. and/or Sum criteria failed.).
4. Test your program on the following data entered into a text file (the first header line is just for informational use only and should not be included in the actual input file):
Any help on how to begin and set up the program correctly would be appreciated.
Explanation / Answer
please rate - thanks
import java.util.*;
import java.io.*;
import java.text.*;
public class MagicsquareTester
{public static void main(String[] args)throws FileNotFoundException
{DecimalFormat threedigit = new DecimalFormat("#00 ");
String formattednumber;
int n,i,j,total,tot;
boolean sum=true, seq=true;
Scanner in=new Scanner(new File("input.txt"));
n=in.nextInt();
int [][]square = new int[n][n];
boolean []num = new boolean [n*n];
for(i=0;i<n*n;i++)
num[i]=false;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{square[i][j]=in.nextInt();
num[square[i][j]-1]=true;
}
System.out.println("The Square");
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{formattednumber= threedigit.format(square[i][j]);
System.out.print(formattednumber);
}
System.out.println();
}
System.out.print("Main diagnol Total: ");
tot=0;
for(i=0;i<n;i++)
tot+=square[i][i];
System.out.println(tot);
total=tot;
System.out.println("Row Totals: ");
for(i=0;i<n;i++)
{tot=0;
for(j=0;j<n;j++)
tot+=square[i][j];
System.out.println("Row "+i+" sum: "+tot);
if(tot!=total)
sum=false;
}
System.out.println("Column Totals: ");
for(j=0;j<n;j++)
{tot=0;
for(i=0;i<n;i++)
tot+=square[i][j];
if(tot!=total)
sum=false;
System.out.println("Column "+j+" sum: "+tot);
}
System.out.print("Anti diagnol Total: ");
tot=0;
for(i=0;i<n;i++)
tot+=square[i][n-i-1];
if(tot!=total)
sum=false;
System.out.println(tot);
for(i=0;i<n*n;i++)
if(!num[i])
seq=false;
if(!sum)
System.out.println("Not Magic square do to sum error");
if(!seq)
System.out.println("Not Magic square do to seq error");
if(sum&&seq)
System.out.println("Magic square");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.