首页 > 解决方案 > 如何在二维数组中查找和打印搜索元素的位置(行和列)?

问题描述

我是一个完整的编程新手,目前正在学习数组。我想7在控制台中打印出数字,这很有效。现在,我还想打印出数字 7 所在的特定行和行:“7 位于第 2 行和第 1 行。”。如何找到数字的行和列7

public static void main(String[] args) {
      
        int[][] array2 = {
                {3,4,5},
                {1,3,6},
                {5,7,9}
        };
        System.out.println(array2[2][1]);
    }
}

标签: javaarrays

解决方案


public static void main(String[] args) {
    int elementSearched = 7;
    int[][] array2 = {
            {3, 4, 5},
            {1, 3, 6},
            {5, 7, 9}
    };

    for (int i = 0; i < array2.length; i++)
        for (int j = 0; j < array2[0].length; j++) {
            if (array2[i][j] == elementSearched) {
                System.out.println(elementSearched + " is located in line " + i + " and row " + j + ".");
            }
        }
}

array2[0] 用于获取行的 sizew(本例中为 3)

这里要做的主要事情就是通过 2 个 for 循环对数组进行蛮力搜索。


推荐阅读