我希望有人可以幫助我。我的問題是我在 Java 中有一個 2D int 陣列。它看起來像這樣:

我需要找到最后2一行的索引0。我已經嘗試用每個回圈的逆函式向后迭代,但這只是反映了整個陣列。我需要的只是索引號。在這種情況下,它應該是 row 0col 3。
我也嘗試在 while 回圈中執行此操作,但它也沒有列印出正確的值,我也不知道為什么。它只列印 2。
int x = ans.length;
int y = ans[0].length;
System.out.println(x);
System.out.println(y);
while(y - 1>= 0 ) {
System.out.println("In");
y--;
if(ans[0][y] != 0) {
x = ans[0][y];
System.out.println(x);
uj5u.com熱心網友回復:
您不需要向后或反向迭代:
public class StackOveFlow {
static int[][] matrix = {
{2,2,0,2,0,0},
{0,2,2,2,2,2},
{2,2,2,2,2,0},
{0,2,2,0,0,0},
{2,2,2,0,1,1}
};
public static void main(String[] args) {
// TODO code application logic here
int rowToSearch = 0;
int integerToFind = 2;
int lastOccurance = findLastOccurrance(rowToSearch,integerToFind);
if(lastOccurance>-1)
System.out.println("Found last " integerToFind " in row " rowToSearch " at column = " lastOccurance);
else
System.out.println("NOT FOUND");
}
public static int findLastOccurrance(int row, int intToFind)
{
int index = -1;
for(int column = 0; column < 6;column )
if(matrix[row][column]==intToFind)
index = column;
return index;
}
}
如果你有大陣列,反向迭代將很有用。反向迭代可以通過回圈的微小變化來完成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534275.html
標籤:爪哇循环多维数组
上一篇:我想使用python回圈這種格式
