从文本文件中读取单词和数字

时间:2015-04-04 03:15:38

标签: java java.util.scanner java-io

我正在编写一个程序,它读取文本文件并向ArrayList添加唯一的单词和数字。我使用了分隔符,但是当我运行程序时,我得到一个NoSuchElementException。我的分隔符错了还是我犯了另一个错误?

这是我的计划:

import java.util.*;
import java.io.*;
public class Indexer
{
   public static void main(String[] args) throws FileNotFoundException
   {

      Scanner fileScanner = new Scanner(new File("File.txt")).useDelimiter("[.,:;()?!\" \t]+~\\s");
      int totalWordCount = 0;
      ArrayList<String> words = new ArrayList<String>();
      while ((fileScanner.hasNext()) && (!words.contains(fileScanner.next())))
      {
         words.add(fileScanner.next());
         totalWordCount++;
      }
      System.out.println("There are " + totalWordCount + " unique word(s)");
      System.out.println("These words are:");
      System.out.println(words.toString());
      fileScanner.close();
    }
}    

3 个答案:

答案 0 :(得分:2)

这应该可行,您可以使用tostring或迭代器来显示单词:

Set<String> words = new HashSet<String>();
      while ((fileScanner.hasNext())) { 
               words.add(fileScanner.next());
      }
      System.out.println("There are " +  words.size() + " unique word(s)");
      System.out.println("These words are:");
      //System.out.println(words.toString());
      for (Iterator<String> it = words.iterator(); it.hasNext(); ) {
          String f = it.next();
          System.out.println(f);
      }
      fileScanner.close();

答案 1 :(得分:1)

我会使用Set而不是List

Set<String> words = new HashSet<String>();
while (fileScanner.hasNext()) { 
      words.add(fileScanner.next());

答案 2 :(得分:1)

NoSuchElementException很可能来自while循环中的第二个fileScanner.next()。

当到达文件中的最后一个元素时,它会在while循环条件下从fileScanner.next()中读取,导致在循环内进行第二次fileScanner调用时没有剩余元素。

一种解决方案可能是每次迭代调用一次fileScanner.next():

  Scanner fileScanner = new Scanner(new File("File.txt")).useDelimiter("[.,:;()?!\" \t]+~\\s");
  int totalWordCount = 0;
  Set<String> words = new HashSet<String>();
  String nextWord;
  while ((fileScanner.hasNext()) && (!words.contains(nextWord = fileScanner.next())))
  {
     words.add(nextWord);
     totalWordCount++;
  }
  System.out.println("There are " + totalWordCount + " unique word(s)");
  System.out.println("These words are:");
  System.out.println(words.toString());
  fileScanner.close();
}