The problem is: Check to see if the array arr2 is contained within the arr1 in the same order. The arr2 could be contained anywhere with in arr1.
public boolean contains(String[] arr1, String[] arr2)
{
int length = 0;
if(arr2.length > arr1.length)
return false;
for(int i = 0; i < arr2.length; i++)
{
if(arr2[i] == arr1[i])
length++;
}
if(length == arr2.length)
return true;
else
return false;
}
TESTER: contains({"1", "2", "3"}, {"1", "2"}) → true
RUN: TRUE
TESTER: contains({"1", "2", "3"}, {"2", "3"}) → true
RUN: FALSE
TESTER: contains({"1", "2", "3"}, {"2", "1"}) → false
RUN: TRUE
TESTER: contains({"MARY", "A", "LITTLE", "LAMB"}, {"A", "LITTLE", "LAMB"}) → true
RUN: FALSE
TESTER: contains({"MARY", "A", "LITTLE", "LAMB"}, {"MARY", "A", "LITTLE", "LAMB"}) → true
RUN: TRUE
.
I don't know where I'm going wrong. Thanks for help.
-
Hint: you need a nested for loop.mdnghtblue– mdnghtblue12/09/2014 01:00:38Commented Dec 9, 2014 at 1:00
-
@mdnghtblue: Actually, you don't, though it can certainly be done that way.Scott Hunter– Scott Hunter12/09/2014 01:02:07Commented Dec 9, 2014 at 1:02
2 Answers 2
- use
arr[1].equals(arr[2])
insteadarr[1] == arr[2]
- should judge in the loop not before loop
I modify the code like it:
public static boolean contains(String[] arr1, String[] arr2) {
int length = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr2[length].equals(arr1[i])) {
length++;
} else {
length = 0;
}
if (length == arr2.length)
return true;
}
return false;
}
You are only comparing both arrays from the beginning; you need to also consider the cases when you start comparing at a different location in arr1
. For example, you would get TRUE in the second example if you started comparing at the second element of arr1
(same for the fourth example).
-
So how do I start comparing at the second element of arr1? I tried at the if statement to do
if(arr2[i] == arr1[i] || arr2[i] == arr1[i+1])
but it doens't work.byerlyfactor– byerlyfactor12/09/2014 01:54:26Commented Dec 9, 2014 at 1:54