0

Hello I create a 2D array and i want to find the position from the first 2 in the array. And after to add the index in a new ArrayList. But this code doesn't work. Any idea for the problem?

import java.util.ArrayList;

class Test {
    public static void main(String[] args) {

        ArrayList<Integer> tableau = new ArrayList<Integer>();
        int[][] tab = {
                        {1,1,1,1,1,1,2,1,1,2,1,1,1,2,1,2,1,1,1,1,1},
                        {1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1},
                    };

        for (int i = 0; i < tab.length; i++) {
            int j = tab[i].indexOf(2);
            for (int k = j ; k < tab[i].length; k++) {
                if (tab[i][j] == 2){
                    tableau.add(j);
                }
            }

        }
        for (Integer row : tableau) {
                System.out.println("row = "+ Arrays.toString(tableau));
        }
    }
}
  • What isn't working, do you have an error message you can include? – Lima Oct 22 '15 at 13:18
  • ??? Is not a array tab? This is the method shows at my school for create an 2D array –  Oct 22 '15 at 13:24
  • @Lima Yes I have Test.java:15: error: cannot find symbol int j = tab[i].indexOf(2); ^ symbol: method indexOf(int) location: class int[]. The ^ is under the dot –  Oct 22 '15 at 13:25
  • then your school has bad Java teachers :) – nano_nano Oct 22 '15 at 13:25
  • In this topic there are the same methote ! http://stackoverflow.com/a/18052343/3741098 –  Oct 22 '15 at 13:32
  • where do you see an indexOf method? – nano_nano Oct 22 '15 at 13:36
  • 1
    What are you attempting to accomplish? Even if the code executed, it would not accomplish what you are trying to do. You don't even use the `k` index in your inner for loop. And you are printing the entire ArrayList for each item in your ArrayList. If this code was even able to execute it would print something like `row = 0, 0, 0, 0, 1`, but it would print it 5 times. It is very unclear what you are even attempting to do with the program in general, even after your syntax errors are fixed. – Andrew Mairose Oct 22 '15 at 13:41

1 Answers1

0

As others have mentioned, regular arrays do not have an indexOf method, meaning that you will get an error when you compile.

However, you can easily create your own method to use as a substitute.

private static int indexOf(int value, int[] array)
{
    for (int i=0; i<array.length; i++)
    {
        if (array[i] == value)
            return i;
    }
    return -1;
}

Then you can just replace this line:

int j = tab[i].indexOf(2);

With this one:

int j = indexOf(2, tab[i]);
Mage Xy
  • 1,803
  • 30
  • 36