如何在Java中使用BufferedReader计算文件中单词的出现次数

如何在Java中使用BufferedReader计算文件中单词的出现次数,java,string,filereader,reader,Java,String,Filereader,Reader,任务是查找文件中特定单词的出现次数 那个人自己写的 public void reader() { BufferedReader myR = myReader("enter the name of a file: "); int count = 0; String substring = readLine("enter the string to count for entry: "); try { while (true) {

任务是查找文件中特定单词的出现次数 那个人自己写的

public void reader() {
    BufferedReader myR = myReader("enter the name of a file: ");
    int count = 0;
    String substring = readLine("enter the string to count for entry: ");
    try {
        while (true) {
            String s = null;
            s = myR.readLine();
            if (s == null)
                break;
            for(int j=0; j<s.length(); j++){
                if(s.contains(substring)){
                    count++;
                }
            }
        }
        myR.close();
    } catch (IOException e) {
        throw new ErrorException(e);
    }
    println("number of words is: " + count);
}

private BufferedReader myReader(String prompt) {
    BufferedReader rd = null;
    while (rd == null) {
        try {
            String name = readLine(prompt);
            rd = new BufferedReader(new FileReader(name));
        } catch (FileNotFoundException e) {
            println("wrong file entered");
            // e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return rd;
}

所以问题是,如果在我的文本文件中我检查的单词数是4,我不知道该怎么办,但代码打印671个,问题在于这个循环:

while (true) {
        String s = null;
        s = myR.readLine();
        if (s == null)
            break;
        for(int j=0; j<s.length(); j++){
            if(s.contains(substring)){
                count++;
            }
        }
    }
现在假设您的bufferedReader读取一行hie i am user

此字符串的大小为13 so string.length;将返回13

这意味着您将为您的匹配检查同一行13次迭代

所以,假设你正在寻找一个匹配的用户,比如说用户,那么在同一行上检查用户13次会使你的计数上升到13

您可以使用此代码替换上述代码:

while (true) {
        String s = null;
        s = myR.readLine();
        if (s == null)
            break;
        String[] slist = s.split(" ");
        for(int j=0; j<slist.length(); j++){
            if(slist[j].contains(substring)){
                count++;
            }
        }
    }

哦!!您应该提到,您希望在不使用数组的情况下执行此操作

此代码段应该可以帮助您:

while (true) {
        String s = null;
        s = myR.readLine();
        if (s == null)
            break;
        for(int j=0; j<s.length(); j++){
            if(s.equals(" ")){
                String temp = s.substring(j+1, s.length());
                String word = temp.substring(0,temp.indexOf(" ")-1);
                if(temp.equalsIgnoringCases(word)){
                   count++;  
                }
            }
        }
    }
现在我在这里做的是,首先,我在整个字符串中寻找一个空格,找到一个空格后,我提取一个子字符串,从空格索引旁边的索引开始,一直到字符串的末尾


现在从这个提取的子串,我进一步从索引0提取一个子串,直到第一个空间。这个字符串本质上是一个适合比较的单词。

forint j=0;jbe由于while中的for循环loop@Jens不,不是因为这个。非常感谢,但问题是我不能在这里使用数组task@Student查找子字符串第一次出现的索引。如果找到,则递增计数,并找到子字符串的下一个匹配项,即从第一个匹配项的末尾开始,等等@Student是否有帮助?