首页 > 解决方案 > 在二维数组中搜索特定行

问题描述

我试图在二维数组中找到特定的第 n 行:

    public static String searchNum(int[][] playerArr, int[]winNum, int playerId) {
    // Take in an ID (row) and based on that, check the numbers against the winning numbers and display which category they fall.

    for(int i = 0; i < playerArr.length; i++) { // Loop over the rows (ID's)

        if(playerArr[i] == playerId)){ // If current row = input (player id)
            int currID = i;
            int counter = 0;

            for (int j = 0; j < playerArr[i].length; j++) { // i = row
                int currLottNum = winNum[j];

                boolean contains = IntStream.of(playerArr[i]).anyMatch(x -> x == currLottNum);
                if(contains) {
                    counter ++;
                }
            }

            // Add to array depending on number of matches
            switch(counter) {
                case 6 : winners.add(currID);
                    break;
                case 5 : fifthPlace.add(currID);
                    break;
                case 4 : fourthPlace.add(currID);
                    break;
                case 3 : thirdPlace.add(currID);
                    break;
                default : losers.add(currID);
            }
        }
    }

    return strRes;
}

我正在尝试将 2D 数组 (playerArr[i]) 的行与给定的 int 进行比较,但它不会让我“运算符 '==' 不能应用于 int[]”

任何帮助表示赞赏。

亲切的问候,

标签: javaarrays

解决方案


正如我所见, playerArr是一个二维数组,而playerArr[i]将返回一个一维数组。因此,您无法将两者进行比较。现在,如果您想比较每个玩家 ID,那么您的代码应该是这样的:

public static String searchNum(int[][] playerArr, int[] winNum, int playerId) {
    // Take in an ID (row) and based on that, check the numbers against the winning numbers and display which category they fall.

    for (int row = 0; row < playerArr.length; row++) { // Loop over the rows (ID's)

        for (int column = 0; column < playerArr[row].length; column++) { // Loop over columns
            if (playerArr[row][column] == playerId) { // If current row = input (player id)
                // your logic
            }

        }
    }
    return strRes;

}

推荐阅读