[英]Iterating through the subdiagonal of a 2D Array
我正在嘗試遍歷隨機生成的0和1的2d數組。 在我堅持的這種方法中,我試圖查看對角線是否具有相同的數字,全1,全0或不同的數字。
子對角線含義:
110
101
011
0是對角線。
這是我到目前為止的代碼。 我試圖從最后一行開始迭代,對角線計數到第一行。
int firstValue= matrix[matrix.length-1][0];
int result = -1;
for(int row = matrix.length-1; row > 0; row--)
{
int column = row;
if(firstValue == matrix[row][column])
{
result = firstValue;
continue;
}
else
{
result = -1;
break;
}
}
if(result== 1)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else if (result == 0)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else
{
System.out.println("Numbers on subdiagonal are different");
}
}
我幾乎可以確定我的問題是firstValue和/或for循環計數對角線。 任何幫助,將不勝感激,非常感謝
您的問題似乎在以下幾行,
for(int row = matrix.length-1; row > 0; row++) {
...
}
你正在做一個
row = matrix.length-1; // row = array length - 1
row++ //this will increase the row's value beyond your array length
然后,您將訪問一個不存在的索引,導致ArrayIndexOutOfBoundsException
編輯
你想做的是
for(int row = matrix.length-1; row >= 0; row--) {
....
}
這樣,您就可以從最大索引到最小索引(0)遍歷數組。
編輯2
假設稱為arr的Staring數組具有4個元素。 它的結構如下
arr[0] = "test1";
arr[1] = "test2";
arr[2] = "test3";
arr[3] = "test4";
數組索引始終從0開始,因此上述數組中的最高索引為3。
因此,如果您要從最小的索引迭代到最大的索引,則可以
for(int i = 0; i < arr.length; i++) {
//i's initial value is 0 and itll increment each time the loop runs
//loop will terminate when i is no longer < 4
System.out.println(arr[i]);
}
並以相反的順序遍歷數組,
for(int i = (arr.length - 1); i <= 0; i--) {
//i's initial value is (4 - 1) and it'll decrement each time the loop runs
//loop will terminate when i smaller or equal to 0
System.out.println(arr[i]);
}
因此,我們要檢查對角線中的所有值是否都相同,如果是,那么我們要打印相同的值。 首先我們擱置一個比較以檢查其他指標
int checkValue = arr[0][arr[0].length-1];
這是第一行中的最后一個值。 然后,我們設置一個標記以在我們正在檢查的索引與第一個值匹配時進行捕獲。 我們將其設置為false,因為我們假設值不匹配。
boolean flag = false;
現在我們有了這個,我們需要遍歷數組中的每一行。 我們將從第二行(arr [1])開始,然后我們需要將值與上次檢查的值(arr [1] [arr.length-1-i])進行比較,然后向下和向上檢查一個值。 如果我們的第一個值(我們將其值分配給checkValue)和我們要檢查的值相同,則將標志更改為true。
for (int i = 1; i < arr.length; i++)
if (arr[i][arr.length - 1 - i] != checkValue)
flag = true;
這將遍歷數組中的所有行。 現在,我們必須檢查標志的狀態並打印出適當的響應。 如果該標志為true,則打印出該行上的值相同。 否則,我們將說次對角線一直都不匹配。
if (!flag)//remember our flag is set to false, double negative equals true.
System.out.println("All of the values on the subdiagonal are the same");
else
System.out.println("All of the values on the subdiagonal are not the same");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.