搜索方法只搜索第一行java

时间:2014-03-03 01:21:20

标签: java bufferedreader stringtokenizer

似乎我的搜索方法只搜索第一行,没有别的。不知道为什么。它应该逐行读取匹配,如果没有找到,则向前移动到下一行,直到所有行都耗尽,但是当我用一个有多行的文件测试它并在第5行搜索一个字符串时它返回:在文件中找不到搜索参数。

String Search(String key) throws IOException {

int lines = 0;
String line = "";
String nextLine = "";
String foundAt = "";
BufferedReader BR = new BufferedReader(new FileReader(f));

try  {
   while ((nextLine = BR.readLine()) != null) {
      line = nextLine.toLowerCase();
      lines++;
      StringTokenizer words = new StringTokenizer(line); //create tokenizer words with what is in line
      while(words.hasMoreTokens()) { //while words has tokens left
         if (words.nextToken().equals(key.toLowerCase())) //go to next token and compare to key
            foundAt = foundAt + "\n" + lines + ": " + line;

            //do nothing continue loop                     
         }
      }
      BR.close();
   }  catch(FileNotFoundException e)  {
   }
   if (foundAt == "")
   foundAt = "Search parameter NOT found in file.";
   return foundAt;
}

1 个答案:

答案 0 :(得分:1)

我看到代码完全没问题,我尝试使用以下测试文件:

word line
number two
alice and bob
bar bazz
loop for each
buzz bizz bar bozz
this is some text
lorem ipsum bar
buzz isobar

搜索“bar”:

System.out.println(Search("bar"));

我得到了以下(预期)结果:

4: bar bazz
6: buzz bizz bar bozz
8: lorem ipsum bar

所以,它正确识别包含单词的行(它甚至会跳过包含“bar”的最后一行作为另一个单词的一部分)。

我最好的猜测是你传递了一个错误的文件路径,所以你有一个FileNotFoundException,但由于你忽略了它,你没有堆栈跟踪,没有什么可以帮助你。尝试在catch子句中打印异常,并重新运行程序:

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

我的第二个最好的猜测是你的测试用例很糟糕(比如你正在搜索的字符串是另一个单词的一部分,或者如果你在单词之后有一些标点符号)。尝试运行我的测试用例,看看它是否有效。