搜索2D int [] []数组?

时间:2014-11-17 22:07:35

标签: java arrays search int 2d

如何在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.
} 

这是我学校作业的一部分,只需指点就可以了。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试使用这样的方法来迭代数组的两个维度并检查当前位置而不是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");
                }
            }
        }

答案 1 :(得分:0)

这条线在两个方面有误:

 if(graph[4][4] == '1')
  1. '1'周围的引号使其成为char字面值。由于您的数组包含int,因此您需要删除引号并只写1

  2. graph[4][4]将始终检查数组中的相同值。具体来说,它将始终访问第二个数组的第五个数组中的第五个值。无论何时在代码中编写数字,它们都是常量:数字4在程序执行期间永远不会改变,所以你一遍又一遍地使用4作为索引,每次访问时都要访问第五个元素。

  3. 为了访问数组中的每个元素,您可以像这样遍历它:

    for (int n = 0; n < array.length; n ++)
    {
        array[n]; //access the nth element of the array
    }
    
    此实例中的

    n与您的edge变量相同。

    但是,由于您使用的是二维数组,因此这些元素本身就是数组!因此,您需要另一个循环:

    //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.
        }
    }
    

    我们为索引使用变量,以便它们可以在循环中更改并访问数组中的不同值。希望这有帮助!

相关问题