在Java中通过haystack(较大的字符串数组)筛选针(字符串数组)

在Java中通过haystack(较大的字符串数组)筛选针(字符串数组),java,arrays,string,Java,Arrays,String,我需要返回干草堆中何处的索引位置 数组出现针数组,否则为-1。例如,如果StringhaystackArray=[red,blue,green]和Stringneederarray=[blue,green]则针出现的haystack的1索引位置应返回1 下面是我的代码的样子: public static int FindSequence(String[] haystack, String[] needle) { int numInSequence = 0;

我需要返回干草堆中何处的索引位置 数组出现针数组,否则为-1。例如,如果String
haystackArray=[red,blue,green]
和String
neederarray=[blue,green]
则针出现的haystack的1索引位置应返回1

下面是我的代码的样子:

    public static int FindSequence(String[] haystack, String[] needle)
    {
        int numInSequence = 0;
        int counter = 0;

        if(haystack.length == 0 || needle.length == 0)  
            return -1;
        if(needle.length > haystack.length)
            return -1;
        for(int i = 0; i < haystack.length-1; i++) //for the length of haystack
        {
            if(needle[0].equals(haystack[i]))//if the first item in needle is equivalent to this particular item in haystack...
            {
                numInSequence = i;
                numInSequence+=1;
                for(int j = 1; j < needle.length-1; j++, numInSequence++){ //for the remaining length of the needle... 
                    if(needle[j].equals(haystack[numInSequence])){ //checks to see if the next item in needle is equivalent to the next item in haystack and if this 
                        counter++;
         if((needle[needle.length-1]).equals(haystack[numInSequence])){ // if the last item in needle is equivalent to an item in haystack...
                            return numInSequence - counter - 1; // return our desired index
                        }
                    }     
                    break;
                }
                break;
            }
        } 
        return -10;
    }  
publicstatic int-FindSequence(字符串[]haystack,字符串[]针)
{
int numInSequence=0;
int计数器=0;
if(haystack.length==0 | | pinder.length==0)
返回-1;
if(针.长度>干草堆.长度)
返回-1;
for(int i=0;i

出于某种原因,几乎所有我尝试的数组测试都会返回-10。如有任何建议或帮助,将不胜感激。

将循环条件更改为

for(int i = 0; i < haystack.length; i++)
返回
returnnuminsequence-counter-1。这就是bug的来源

举个例子,如果数组中有10个元素,则索引为0-9。您正在检查<9而不是<10。因此,代码不会检查索引9。

调整if((针[Pineer.length-1])的缩进。等于(haystack[numInSequence]){。
 for(int j = 1; j < needle.length; j++, numInSequence++){
if((needle[needle.length-1]).equals(haystack[numInSequence])){