[英]searching a 2D int[][] array?
如何在2D數組中搜索特定數字(1)? 我以為下面的代碼可以做到這一點,但是當我用[4] [4]聲明它時,顯然我正在尋找特定的位置。
boolean undirectedCircuit (int [][] graph)
{
//graph = graph1(graph1(null));
int edgeCounter = 0;
for (int edge = 0; edge < graph.length; edge++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if(graph[4][4] == '1')
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
if (edgeCounter % 2 == 0)
{
System.out.println("This is a circuit!");
//return true;
}
else System.out.println("This is not a circuit!!");
return false;
}
public void go ()
{
graph1 = new int[][] //This line is complained about.
{
{0,1,1,1,0},
{1,0,0,0,1},
{1,0,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}
};
undirectedCircuit(graph1); //This is complained about.
}
這是我學校分配的作業的一部分,只是指針會很棒。 謝謝!
您可以嘗試執行類似的操作,在其中遍歷數組的兩個維度並檢查當前位置,而不是4,4
for (int x = 0; x < graph.length; x++)
{
for (int y = 0; y < graph[x].length; y++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if (graph[x][y] == 1)
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
}
此行有兩種錯誤的方式:
if(graph[4][4] == '1')
'1'
周圍的引號使它成為char
文字。 由於您的數組包含int
,因此您需要刪除引號並只寫1
。
graph[4][4]
將始終檢查數組中與您說的值相同的值。 具體來說,它將始終訪問2d數組的第五個數組中的第五個值。 每當您在代碼中寫入數字時,它們都是常量:數字4在程序執行期間永遠不會改變,因此您將一遍又一遍地使用4作為索引,每次這樣做都訪問第五個元素。
為了訪問數組中的每個元素,您可以像這樣遍歷它:
for (int n = 0; n < array.length; n ++)
{
array[n]; //access the nth element of the array
}
在這種情況下, n
與您的edge
變量相同。
但是,由於您使用的是2d數組,因此這些元素本身就是數組! 因此,您需要另一個循環:
//array is a 2d array...
for (int n = 0; n < array.length; n ++)
{
//...so its elements are 1d arrays
for (int m = 0; m < array[n].length; m ++)
{
array[m][n]; //here we have a specific object in our 2d array.
}
}
我們使用變量作為索引,以便它們可以在循環中更改並訪問數組中的不同值。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.