# How to check if all elements in an array are the same?

I made this game for my exam where I have this two dimensional (int [] [] M = new int [30][30]) array that has 3 possible values: 0 (black tile), 1 (white tile) and 2 (fruits). The player can click with the left mouse button to create walls and then press Enter to start playing.

What I want is to display a game over message with a black background once all fruits are eaten. I can’t get this to work, though.

I think I could do it if I could check if all elements on M are different than 2, but I haven’t been able to do that right. Does anybody have any idea how to do this?

1 Like

Given the value `2` means fruit we just need to check for its presence within your 2D array.

If we don’t find that value it means all fruits have been eaten.

The function below returns `true` if a 2D array contains() a specified value otherwise `false`:

``````static final boolean contains(final int val, final int[][] arr2d) {
for (final int[] arr1d : arr2d)  for (final int v : arr1d)
if (v == val)  return true;
return false;
}
``````

Invoke it passing the value `2` as 1st argument and your M 2D array as 2nd argument.

Then if it returns `false` you know all fruits are gone and you can display your game over message.

2 Likes

This worked, thank you so much!!