indexOf(String)链表char逻辑错误

时间:2016-02-15 03:55:39

标签: java algorithm linked-list logic indexof

第一年CS学生。我试图在我的自定义MyStringbuilder类中实现indexOf(String)方法(在这种情况下使用char的链接列表)。我无法获得正确的输出,以便在前面找到查询字符串或找不到它,但是在初始字符串中间的任何内容都不起作用。以下是我的测试驱动程序中的具体示例。

public int indexOf(String str)
    {
        int index =-1; //index at which str is first found in linked list string of chars
        int count = 0; //num of matches
        int firstI = -1;
        int sI=0; // dynamic counter variable to allow str.length and for loop to interact
        CNode currNode = firstC;
        for (int i = 0; i < length; i++)
        {
            if (currNode.data == str.charAt(sI))
            {
                if (count < 1)
                    firstI = i;
                count++;
            }

            if (count == 0 && (sI == str.length()-1))
                sI=0;

            if (count == str.length())
            {
                index = firstI;
                break;
            }

            if (count > 0 && currNode.data != str.charAt(sI))
            {
                sI = 0;
                count = 0;
            }


            currNode = currNode.next; //increment
            sI++;
        }

        return index;
    }

测试驾驶员课程

System.out.println("\nTesting indexOf method");
        b1 = new MyStringBuilder("who is whoing over in whoville");
        String s1 = new String("who");
        String s2 = new String("whoing");
        String s3 = new String("whoville");
        String s4 = new String("whoviller");
        String s5 = new String("wacky");
        int i1 = b1.indexOf(s1);
        int i2 = b1.indexOf(s2);
        int i3 = b1.indexOf(s3);
        int i4 = b1.indexOf(s4);
        int i5 = b1.indexOf(s5);
        System.out.println(s1 + " was found at " + i1);
        System.out.println(s2 + " was found at " + i2);
        System.out.println(s3 + " was found at " + i3);
        System.out.println(s4 + " was found at " + i4);
        System.out.println(s5 + " was found at " + i5);

1 个答案:

答案 0 :(得分:0)

您不在循环内的任何位置设置firstI,但它会返回您返回的值。这将始终返回-1。

此外,我认为您可能想要再看一下变量sI,它似乎没有任何实际用途。如果算数永远!= sI那么你有一个问题,所以你可以完全摆脱sI。