【问题标题】:Using tokenizer to count number of words in a file?使用标记器来计算文件中的单词数?
【发布时间】:2014-03-02 19:17:22
【问题描述】:

我正在制作一个程序,让用户选择一个文件,然后程序从文件中读取。现在我被告知要使用 bufferedreader 和 string tokenizer 来制作程序。到目前为止,我让程序打开文件并计算行数。但是字数就没那么容易了。

这是我目前的代码:

int getWords() throws IOException
{
   int count = 0;
   BufferedReader BF = new BufferedReader(new FileReader(f));
   try  {
      StringTokenizer words = new StringTokenizer(BF.readLine()); 
      while(words.hasMoreTokens())
      { 
         count++;
         words.nextToken(); 
      }
      BF.close();
   }  catch(FileNotFoundException e)  {
   }    
   return count;
}

缓冲阅读器一次只能读取一行,但我不知道如何让它读取更多行。

【问题讨论】:

  • 你做一个while循环直到readLine()返回null
  • while (BF.readLine() != null) 你的意思是?我试过了,没用。
  • 请不要吞下你的例外:stackoverflow.com/questions/921471/…

标签: java bufferedreader stringtokenizer


【解决方案1】:

要计算单词,您可以使用 countTokens() 而不是循环

读取所有行使用

String line = null;
while(null != (line = BF.readLine())) {
StringTokenizer words = new StringTokenizer(line); 
   words.countTokens();//use this value as number of words in line
}

【讨论】:

  • BasicFile.java:117: 错误:意外类型 while(null != line = BF.readLine()) ^ 必需:找到变量:值
  • 很抱歉那里丢失了牙套。现已修复
【解决方案2】:

正如您所说,缓冲阅读器一次将读取一行。因此,您必须阅读行,直到没有更多行为止。 readLine() 到达文件末尾时返回 null。

所以做这样的事情

int getWords() throws IOException {
  int count = 0;
  BufferedReader BF = new BufferedReader(new FileReader(f));
  String line;
  try {
    while ((line = BF.readLine()) != null) {
      StringTokenizer words = new StringTokenizer(line); 
      while(words.hasMoreTokens()) { 
        count++;
        words.nextToken(); 
      }    
    }
    return count;
  } catch(FileNotFoundException e)  {
  } finally {
    BF.close();
  }
  // Either rethrow the exception or return an error code like -1.
}

【讨论】:

  • 你是天赐之物!!谢谢。此外,我们还没有真正学会在课堂上使用异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多