我有一個家庭作業問題,我有麻煩調試。程序的目的是說明哪些行和列具有相同的數字,以及主要和次要對角線。到目前爲止,我已經找到了相同的行和列,然後將它們打印出來。Java - 二維陣列板計數器
這裏是程序的輸出迄今:
0 0 0 0 0 0 0 0
0 0 1 0 1 0 0 0
0 0 0 0 1 0 1 0
0 0 1 0 0 1 1 0
0 0 1 0 0 1 1 0
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0
0 0 1 1 1 1 1 0
All 0 on row 0
All 0 on column 0
All 0 on column 1
All 0 on column 1
All 0 on column 7
All 0 on column 7
正如你可以看到列打印重複了,我想不通爲什麼和如何解決它。我也有一個問題,它不會顯示行6,因爲它們都是一樣的。
我的期望輸出應該是:
All 0 on row 0
All 0 on row 6
All 0 on column 0
All 0 on column 1
All 0 on column 7
預先感謝您。
import java.util.Scanner;
public class javaTest
{
// Main method
public static void main(String[] args)
{
int[][] array = {
{0,0,0,0,0,0,0,0},
{0,0,1,0,1,0,0,0},
{0,0,0,0,1,0,1,0},
{0,0,1,0,0,1,1,0},
{0,0,1,0,0,1,1,0},
{0,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,1,1,1,1,1,0}
};
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();
}
checkRow(array);
checkCol(array);
}
// Check if the row is the same
public static void checkRow(int array[][])
{
String checkRow = "";
int rowCount = 0;
int count = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length;j++)
{
// Create a new array to compare
int num = array[i][j];
for(int k = 0; k < array[i].length; k++)
{
// Check if the first number of the row is equal to the next
if(num == array[j][k])
// If so increment count
count++;
else
count = 0;
}
// If all numbers of the row is the same, total would be 8 and print
if(count == array.length)
System.out.println("All " + num + " on row " + rowCount);
}
rowCount++;
}
}
// Check if column is the same
public static void checkCol(int array[][])
{
String checkCol = "";
int colCount = 0;
int count = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
int num = array[i][j];
for(int k = 0; k < array[i].length; k++)
{
if(num == array[k][i])
count++;
else
count = 0;
}
if(count == array.length)
System.out.println("All " + num + " on column " + colCount);
}
colCount++;
}
}
}
謝謝!還有一件事,找到董事會主要和次要對角線的好方法是什麼? – Flinze