/ **我正在使用二维数组创建一个完美的正方形。在程序中,每行,每列和对角线必须彼此相等。我的 checkArrays 方法需要帮助。我对 checkArrays 方法的意图是检查每个数组是否彼此相等,如果一个数组彼此不相等,那么它不是一个完美的正方形(返回false)。 * /
公共类PerfectSquare {
static Scanner sc;
static int[][] magicS;
/**
* Builds perfect square
*/
public static void buildSquare() {
magicS = new int[3][3];
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
//asks the user to input a number.
System.out.println("Please type number for column " + (r + 1) + " and row " + (c + 1));
magicS[r][c] = sc.nextInt();
}
}
}
/**
* Prints perfect square
*/
public static void printSquare() {
for (int r = 0; r < 3; r += 1) {
for (int c = 0; c < 3; c += 1) {
System.out.print(magicS[r][c] + " ");
}
System.out.println("");
}
}
/**
* Adds each row together
*
* @param r
* @return
*/
public static int getRowSums(int r) {
int sum = 0;
for (int c = 0; r < magicS[r].length; c++) {
sum += magicS[r][c];
}
return sum;
}
/**
* Adds each colum together
*
* @param c
* @return
*/
public static int getColSums(int c) {
int sum = 0;
for (int r = 0; r < magicS.length; r++) {
sum += magicS[r][c];
}
return sum;
}
/**
* Adds each diagonal together
*
* @return
*/
public static int[] getDiaganolSums() {
int[] sums = new int[2];
for (int d = 0; d < magicS.length; d++) {
sums[0] += magicS[d][d];
sums[1] += magicS[d][magicS.length - 1 - d];
}
return sums;
}
/**
* Checks to see if the sum of each row, colum, and diagonal should all be
* the same, If perfect returns perfect.
*
* @return
*/
public static boolean checkValid() {
int[] rowSums = new int[magicS.length];
for (int r = 0; r < magicS.length; r++) {
rowSums[r] = getRowSums(r);
}
int[] colsSums = new int[magicS.length];
for (int c = 0; c < magicS.length; c++) {
colsSums[c] = getColSums(c);
}
int[] diagSums = getDiaganolSums();
boolean perfect = checkArrays(rowSums, colsSums, diagSums);
return perfect;
}
/**
* checks if each row, colum, and diagonal are equal to each other
*
* @param r
* @param c
* @param d
* @return
*/
public static boolean checkArrays(int[] r, int[] c, int[] d) {
}
/**
* The main method asks the user to input numbers that correlate to a row
* and column When run, a 3 x 3 array of the numbers inputted will be printed.
*
* @param args
*/
public static void main(String[] args) {
//allows to get info from user
sc = new Scanner(System.in);
//executes the buildSquare method
buildSquare();
//executes the printSquare method
printSquare();
//executes the checkValid method
checkValid();
}
}