目前我正在开发一个程序,用于在8x8的二维数组中生成随机的0和1。我的任务是检查对角线上的所有数字是否相同(从角落开始,而不仅仅是任意对角线)。
例如:
int[][] array = {
{0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 1, 0, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 1, 1, 0, 1, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 1, 0}
};
如果恰巧所有从左上角 (0,0) 开始的数字,如 (1,1)...(7,7),都是 0 或 1 ,那么我需要向扫描仪输出 "存在一个0的主对角线"(来自上面的例子)。
此外,从右上角开始,数字 "1" 沿着对角线朝左下方重复,那么我也需要显示 "存在一个1的次对角线"。
到目前为止,我已经知道了如何生成和输入数组中的数字,但我不知道如何进行检查。这是我的工作进展:
public class JavaTest{
// Main method
public static void main(String[] args) {
int[][] array = {
{0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 1, 0, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 1, 1, 0, 1, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 1, 0}
};
// Print array numbers
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++)
System.out.print(array[i][j] + " ");
System.out.println();
}
// Print checkers
checkMajorDiagonal(array);
}
// Check major diagonal
public static void checkMajorDiagonal(int array[][]) {
int majDiag;
boolean isMatching = true;
int row = 0;
for(row = 0; row < array.length; row++){
majDiag = row;
if(array[row][row] != array[row+1][row+1]){
isMatching = false;
break;
}
}
//If all elements matched print output
if(isMatching)
System.out.println("Major diagonal is all " + array[row][row]);
}
}
虽然我目前的代码还不能按照我的意愿工作,因为出现了一个错误,而且我还需要处理小对角线。提前感谢您。