127k views
2 votes
Write a method called equals that takes in two string arrays and returns true if they are equal; that is, if both arrays have the same length and contain equivalent string values at each index.

1 Answer

3 votes

Answer:

public boolean equals( String [ ] a, String [ ] b ){

if (a.length == b.length){

for (int i = 0; i < a.length; i++){

if ( ! a [ i ].equals( b [ i ] )) {

return false;

}

}

return true;

}

return false;

}

Step-by-step explanation:

The above code has been written in Java.

// 1. Method header declaration

// Method name is equals.

// It takes in two arguments which are the two string arrays a and b.

// Since the method returns a true or false, the return type is boolean

public boolean equals( String [ ] a, String [ ] b ){

// 2. Check if the two arrays are of same length

if (a.length == b.length){ // Begin outer if statement

// If they are equal in length,

// write a for loop that cycles through the array.

// The loop should go from zero(0) to one less than

// the length of the array - any of the array.

for (int i = 0; i < a.length; i++){

// At each of the cycle, check if the string values at the index which

// is i, of the two arrays are not equal.

if ( ! a [ i ].equals( b [ i ] )) {

// If they are not equal, exit the loop by returning false.

return false;

}

}

// If for any reason, the for loop finishes execution and does not

// return false, then the two arrays contain the same string values at

// each index. Therefore return true.

return true;

} // End of outer if statement

// If none of the return statements above are executed, return false.

return false;

} // End of method.

Hope this helps!

User Ubershmekel
by
4.7k points