Reputation: 57
I am having to compare arrays without using the .equals method and currently the program runs correctly except when I have two variables such as
int[] y = {8,8,8};
int[] z = {8,8,9};
My program says this is true when it should say it is false. The following is my CompareArrays code:
if (arrayOne.length == arrayTwo.length) {
for (int i = 0; i < arrayOne.length; i++) {
if (arrayOne[i] == arrayTwo[i]) {
return true;
}
}
}
return areEqual;
I have to use the boolean areEqual = false
and return it at the end.
Upvotes: 0
Views: 1241
Reputation: 140544
You are returning true as soon as you find a matching pair of elements, and never updating areEqual
. You need to keep going until you find a pair of elements which aren't equal, or reach the end of the array.
Instead, use the areEqual
variable to tell you if you have found something - anything - which makes them unequal. Once you have found something to make them unequal, you don't need to check any more:
boolean areEqual = false; // Redundant assignment; but meh, if you've got to use this...
areEqual = arrayOne.length == arrayTwo.length;
for (int i = 0; areEqual && i < arrayOne.length; ++i) {
areEqual = arrayOne[i] == arrayTwo[i];
}
return areEqual;
Upvotes: 0
Reputation: 664
@Mayhem 's answer is correct. I just want you to show you a more cleaner way (by removing the if
nesting):
if (arrayOne.length != arrayTwo.length) {
return false;
}
for (int i = 0; i < arrayOne.length; i ++) {
if (arrayOne [ i ] != arrayTwo [ i ] ) {
return false;
}
}
return true;
Upvotes: 0
Reputation: 702
Instead of immediately returning when they are equal, check for inequalities and if there's one, then return false
. If the for
loop finishes without returning, then you can safely return true
.
if (arrayOne.length == arrayTwo.length) {
for (int i = 0; i < arrayOne.length; i ++) {
if (arrayOne [ i ] != arrayTwo [ i ] ) {
return false;
}
}
return true;
}
return false;
Upvotes: 3