搜索功能在每个新行上添加索引

时间:2013-07-24 08:25:11

标签: java search loops for-loop

所以我一直在写一个聊天客户端,我决定创建一个搜索功能,这样你就可以在聊天记录中找到一个特定的单词并选择它。然而,会发生的是,初始行下面的每一行选择是它应该选择的单词的许多索引。是否有我缺少的新行字符或索引位置?

如何绕过每行更改的索引? 或者我的代码中可能存在问题:

private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    toSearchText = searchText.getText();
    if (!toSearchText.equals("")) {
        for (int i = index; i < searchBlock.length(); i++) {
            if (searchBlock.charAt(i) == toSearchText.charAt(0)) {
                System.out.println("found first char- Starting check loop." + i + j + "::" + count);
                for (j = i; j < i + toSearchText.length(); j++) {
                    System.out.println("J" + j + " II " + innerIndex);
                    if (searchBlock.charAt(j) == toSearchText.charAt(innerIndex)) {
                        innerIndex++;
                        count++;
                        System.out.println("found char:" + innerIndex + " - " + searchBlock.charAt(j));
                    } else {
                        System.out.println("Not the word");
                        break;
                    }
                }
            }
            System.out.println(i);
            System.out.println(j);

            if (count == toSearchText.length()) {
                if (searchBlock.substring(i, j).equals(toSearchText)) {
                    System.out.println(searchBlock.substring(i, j) + " and " + toSearchText);
                    System.out.println("focusing");
                    ClientWindow.mainText.requestFocusInWindow();
                    ClientWindow.mainText.select(i, j);
                    count = 0;
                    innerIndex = 0;
                    index = i + toSearchText.length();
                    if (index > searchBlock.length()) {
                        index = 0;
                    }
                    break;
                }
            } else {
                System.out.println("focus refused");
            }
        }
        System.out.println("Search Finished");
    }
}                                     

1 个答案:

答案 0 :(得分:0)

好的,那么为了解决每行上有一个额外索引的问题,我写了一个方法来计算行数,然后从索引中减去该值。

private int checkLine(int position){
    int counter = 0;
    Scanner text = new Scanner(searchBlock.substring(0,position));

    while(text.hasNextLine()){
        counter++;
        text.nextLine();
    }
    return counter - 1;
}