我需要使用多种方法来找出用户输入的矩阵中的数字是否使其成为魔术平方(即所有行,列和对角线都具有相等的总和(。由于某种原因,我无法弄清楚如何将每个对角线的总和添加并在第二种方法中相互比较。我还需要提出一种方法来找到每一行的总和,并将它们相互比较以达到等效。然后,我需要像排成行一样做另一个方法,除了列。
。/**
* all rows, columns, and diagonals = the same sum
*
* @author Jenny Nguyen
* @version 5-6-19
*/
import java.util.Scanner;
public class MagicSquare
{
public static void main (String [] args)
{
//Declare + initialize
Scanner input = new Scanner(System.in);
int size;
//asks user how big square will be
System.out.println("How many rows and columns will there be in the square?");
size = input.nextInt();
int[][] matrix = new int[size][size];
//calls up method
read2D(matrix, input);
System.out.println("The square looks like this: ");
//pritns matrix
for (int row=0; row<matrix.length; row++)
{
for (int col=0; col< matrix[row].length; col++)
{
System.out.print (matrix[row][col] + "t"); //print the item
}
System.out.println(); //go to next line for next row
}
//calls up other method
//prints if it's a magic square or not
if (diagonals(matrix, size) == false)
System.out.println("This is not a magic square.");
else if (diagonals(matrix,size) == true) //if method compare(matric) == true
System.out.println("This is a magic square.");
else
System.out.println("try again");
//program needs to work for square of any size and values
}
//Method 1
/**
* asks user to enter numbers in the square
*
* @param int[][]
* @return none
*/
public static void read2D(int [][] matrix, Scanner input)
{
for (int row=0; row<matrix.length; row++)
{
for (int col=0; col< matrix[row].length; col++)
{
System.out.print ("Please enter an integer: "); //prompt user
matrix[row][col] = input.nextInt();
}
}
}
//Method 2
/**
* determine whether diagonals are equal or not
*
* @param int[][] matrix, int size
* @return none
*/
public static boolean diagonals(int [][] matrix, int size)
{
int dia1=0;
for (int i=0, j=0; i<size && j<size; i++, j++)
{
//adds diagonal integers left to right
dia1 += matrix[i][j];
}
int dia2=0;
for (int i=0,j=size-1 ; i<size && j>=0 ; i++, j--)
{
//adds diagonal integers right to left
dia2 += matrix[i][j];
}
if (dia1==dia2)
return true;
else
return false;
}
}
正方形中的主要对角线:行的索引等于列的索引
正方形中的次要对角线:行和列索引的总和等于矩阵大小
这是方法(在矩阵中起作用,其中行== cols(:
public void diagonalsSum(int[][] matrix, int size) {
int primaryDiagonalSum = 0;
int secondaryDiagonalSum = 0;
if (rows == cols) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == j) {
primaryDiagonalSum += matrix[i][j];
}
if (i + j == size) {
secondaryDiagonalSum += matrix[i][j];
}
}
}
}
System.out.println("Primary diagonal sum = " + primaryDiagonalSum);
System.out.println("Secondary diagonal sum = " + secondaryDiagonalSum);
}
这是每行总和的方法,适应您的需求,并将每一行与另一行进行比较。
public void sumOfRows(int[][] matrix, int size) {
int[] rowsSum = new int[size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
rowsSum[i] += matrix[i][j];
}
}
int i = 1;
for (int sum : rowsSum) {
System.out.println("Sum of row " + (i++) + " = " + sum);
}
}