Write a method that checks whether all elements in a two-dimensional array are identical. This is what I have so far.
int[][] arr1 = {{2, 2, 8}, {1, 6, 4}, {3, 9, 8}, {5, 6,
1}};
int[][] arr2 = {{7, 7, 7}, {7, 7,
7}, {7, 7, 7}, {7, 7, 7}};
if(matchingVal(array1)) {
System.out.println("Values in arr1 are the same.");
}
if(matchingVal(array2)) {
System.out.println("Values in arr2 are the same.");
}
Solution :
Explanation : Traverse all the elements of the array and check if every element is equal to the first element i.e the element array[0][0].
Following is the Java code for the same :
public class Main {
public static boolean matchingVal(int[][] arr) {
//Assuming all elements are equal to arr[0][0]
int same = arr[0][0];
//traverse the 2-d array
for (int i=0;i<arr.length;i++)
for (int j=0;j<arr[0].length;j++)
if(arr[i][j] != same)
return false;
return true;
}
public static void main(String args[]) {
int[][] arr1 = {{2, 2, 8}, {1, 6, 4}, {3, 9, 8}, {5, 6, 1}};
int[][] arr2 = {{7, 7, 7}, {7, 7, 7}, {7, 7, 7}, {7, 7, 7}};
if(matchingVal(arr1)) {
System.out.println("Values in arr1 are the same.\n");
}
else System.out.println("Values in arr1 are not same.\n");
if(matchingVal(arr2)) {
System.out.println("Values in arr2 are the same.\n");
}
else System.out.println("Values in arr2 are not same.\n");
}
}
Code demo :
Output :
Get Answers For Free
Most questions answered within 1 hours.