Write a Java program that prompts the user to enter two 3-by-3 arrays of integer
ID: 3567740 • Letter: W
Question
Write a Java program that prompts the user to enter two 3-by-3 arrays of integers and displays whether the two are identical.
The two-dimensional arrays m1 and m2 are identical if they have the same contents. Write a method that returns true if m1 and m2 are identical, using the following header:
public static boolean equals(int[ ][ ] m1, int[ ][ ] m2)
Sample runs:
Enter list1: 51 25 22 6 1 4 24 54 6 <- this line is user prompt input
Enter list2: 51 22 25 6 1 4 24 54 6 <- this line is user prompt input
The two arrays are identical
Enter list1: 51 5 22 6 1 4 24 54 6 <- this line is user prompt input
Enter list2: 51 22 25 6 1 4 24 54 6 <- this line is user prompt input
The two arrays are not identical
Explanation / Answer
import java.util.*;
class MatrixEqual{
public static boolean equals(int[][] m1, int[][] m2){
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
if(m1[i][j] != m2[i][j]){
return false;
}
}
}
return true;
}
public static void main(String [] args){
int[][] mat1 = new int[3][3];
int[][] mat2 = new int[3][3];
Scanner in = new Scanner(System.in);
System.out.print("Enter list1:");
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
mat1[i][j] = in.nextInt();
}
}
System.out.print("Enter list2:");
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
mat2[i][j] = in.nextInt();
}
}
if(equals(mat1, mat2)){
System.out.println("The two arrays are identical");
}else{
System.out.println("The two arrays are not identical");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.