0

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

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

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");
    }
}                                     
4

1 回答 1

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;
}
于 2013-07-30T08:03:31.370 回答