Java- 在二维数组中查找索引

Java- finding an index in a 2D array

我有一个主要由连续整数组成的二维数组。我想获取用户的整数输入并找到比用户输入小一的整数的索引。

我已经手动声明了数组中的前两列,其余十二列是从不同数组中随机分配的整数。

public static int[][] board = new int[4][14];

  public static int[][] deal(int[] cards) {


    board[0][0] = 1;
    board[0][1] = 0;
    board[1][0] = 14;
    board[1][1] =0;
    board[2][0] = 27;
    board[2][1] = 0;
    board[3][0] = 40;
    board[3][1] = 0;


    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 12; j++) {
            board[i][j + 2] = cards[j + (i * 12)];
        }

    } return board;

}

我试图找到比用户输入小一的整数,如果后面的整数(在同一行)是 0,则交换 0 和用户输入。 我意识到数组没有内置函数 indexOf 以下代码不会 运行.

 public static int[][] move(int[][] board) {

    int input;
    int place =0;
    if(board.indexOf(input-1) +1 == 0){
        place =board.indexOf(input);
        board.indexOf(input) = 0;
        board.indexOf(input-1) +1 = place;
    }
    return board;

}

如果你真的想使用函数的索引,你需要切换到列表的列表(即ArrayList,Vector等)。那么你的代码将是这样的

public static ArrayList<ArrayList<Integer>> deal(int[] cards) {
   ArrayList<ArrayList<Integer>> board = new ArrayList<ArrayList<Integer>>();
   for(int  i = 0; i < 4; i++) {
       board.add(new ArrayList<Integer>);
   }
   board.get(0).add(1);
   board.get(0).add(0);
   board.get(1).add(14);
   board.get(1).add(0);
   board.get(2).add(27);
   board.get(2).add(0);
   board.get(3).add(40);
   board.get(3).add(0);

   for (int i = 0; i < 4; i++) {
     for (int j = 0; j < 12; j++) {
         board.get(i).add(cards[j + (i * 12)]);
     }
   } 
  return board;
}

您可以做的另一件事(这更好,因为列表在性能方面有开销)是编写您自己的 indexOf() 函数,如下所示 return 一个整数数组,因为在二维数组索引中意味着两个整数(行和列):

int[] indexOf(int [] [] ar, int row, int col, int x) { //this function will find x in 2D array ar(with dimension of row*col) and return the index
   int [] index = new int [2];
   index [0] = index[1] = -1; 
   for(int i = 0; i<row; i++) {
        for(int j = 0; j<col; j++) {
            if(ar[i][j] == x) {
               index[0] = i;
               index[1] = j;
               return index;
            }
        }
    }
    return index;
}