我正在编写一个程序,该程序读取文本文件并向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();
}
}
谢谢!迭代器帮助。我做了一些调整,它的工作方式是我想要的。谢谢! – juliodesa 2015-04-05 00:46:25
很高兴帮助! – Pulse9 2015-04-05 01:34:04