Find the second occurrence of an object in an array

Hello, I am doing a coding project but it requires me to get the second occurrence of an object in an array.

int[][] array = 
{1, 2, 3, 4},
{5, 6, 7, 8},
{1, 2, 3, 4};

How would you get the second occurrence of “1” in the array?

Your array is not valid.

1D array

When you mean a 1D array:




int[] arrayMy = 
  {
  1, 2, 3, 4, 
  5, 6, 7, 8, 
  1, 2, 3, 4
};

int count=0;
int result = -1; 

for (int i = 0; i<arrayMy.length; i++) {
  if (arrayMy[i] == 1) 
    count++;
  if (count==2) {
    println(i);
    result = i; 
    break;
  }
}//for 


println(result);


OR when you mean a 2D array

// 2D array / grid
int[][] arrayMy = 
  { 
  {1, 2, 3, 4}, 
  {5, 6, 7, 8}, 
  {1, 2, 3, 4}
};

int count=0;
int result = -1;
int result2 = -1; 

// nested for-loop 
for (int i = 0; i<arrayMy.length; i++) {
  for (int i2 = 0; i2<arrayMy[i].length; i2++) {
    if (arrayMy[i][i2] == 1) 
      count++;
    if (count==2) {
      result = i;
      result2 = i2;
      break;
    }
  }//for
}//for

println(result, result2);

Thank you, but the first time I tried implementing this it didn’t work. However, then I saw that I kept redefining the count variable in the for loop. After I changed where the declaration was, it worked! Thank you!

1 Like