I'm trying to solve a problem on "practice it", and I'm not able to pass all the tests to it.
The problem is:
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.
I have tried the following code, but the test to the input equals({"a", "b", "a", "c", "a", "d", "a", "e", "a"}, {"x", "b", "a", "c", "a", "d", "a", "e", "a"})
but it doesn't work.
public static boolean equals (String [] txt1, String [] txt2){
boolean result=false;
if(txt1.length==txt2.length){
for(int i=0; i<txt1.length; i++){
if(txt1[i].equals(txt2[i])){
result = true;
}
else {
result = false;
}
}
}
else {
return false;
}
return result;
}
Expected return: false
My return: true
The problem lies in the loop:
for(int i=0; i<txt1.length; i++){
if(txt1[i].equals(txt2[i])){
result = true;
}
else {
result = false;
}
}
The if
gets executed for every single element, so in essence your code only checks if the last element is the same for both arrays, as it overrides previous result = false;
occurrences.
The correct solution is to immediately stop and return false
once a single element is different:
for(int i=0; i<txt1.length; i++){
if(txt1[i].equals(txt2[i])){
result = true;
}
else {
return false;
}
}