APCSA Lab
Content
- Square
- SquareTest
Square
import java.util.Scanner;
public class Square
{
int[][] square;
public Square(int size)
{
square=new int[size][size];
}
public int sumRow(int row)
{
int sumR=0;
for(int i=0;i<square.length;i++){
sumR+=square[row][i];
}
return sumR;
}
public int sumCol(int col)
{
int sumC=0;
for(int i=0;i<square.length;i++){
sumC+=square[i][col];
}
return sumC;
}
public int sumMainDiag()
{
int sumD1=0;
for(int i=0;i<square.length;i++){
sumD1+=square[i][i];
}
return sumD1;
}
public int sumOtherDiag()
{
int sumD2=0;
for(int i=0;i<square.length;i++){
sumD2+=square[i][square.length-i-1];
}
return sumD2;
}
public boolean magic()
{
int index=0;
int[] test=new int[square.length*square.length+2];
for(int i=0;i<square.length;i++){
test[index]=sumRow(i);
index++;
test[index]=sumCol(i);
index++;
}
test[index]=sumMainDiag();
index++;
test[index]=sumOtherDiag();
int flag=test[0];
for(int i=0;i<=index;i++){
if(test[i]!=flag){
return false;
}
}
return true;
}
public void readSquare(Scanner scan)
{
for(int i=0;i<square.length;i++){
for(int j=0;j<square.length;j++){
square[i][j]=scan.nextInt();
}
}
}
public void printSquare()
{
for(int i=0;i<square.length;i++){
for(int j=0;j<square.length;j++){
System.out.print(square[i][j]+" ");
}
System.out.println();
}
}
}
SquareTest
import java.util.Scanner;
import java.io.*;
public class SquareTest
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(new File("C:/Users/15011/Desktop/CSA/In_Class/Array/magicData.txt"));
int count = 1;
int size = scan.nextInt();
while (size != -1){
Square sq1=new Square(size);
sq1.readSquare(scan);
System.out.println("\n******** Square " + count + " ********");
sq1.printSquare();
for(int i=0;i<size;i++){
System.out.println("rows "+(i+1)+": "+sq1.sumRow(i));
}
for(int i=0;i<size;i++){
System.out.println("columns "+(i+1)+": "+sq1.sumCol(i));
}
System.out.println("main diagonal: "+sq1.sumMainDiag());
System.out.println("other diagonal: "+sq1.sumOtherDiag());
System.out.println(sq1.magic()?"It is a magic square":"It isn't a magic square.");
size = scan.nextInt();
count++;
}
}
}