2015-04-04 81 views
1

我正在编写一个程序,该程序读取文本文件并向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(); 
    } 
}  

回答

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(); 
+0

谢谢!迭代器帮助。我做了一些调整,它的工作方式是我想要的。谢谢! – juliodesa 2015-04-05 00:46:25

+0

很高兴帮助! – Pulse9 2015-04-05 01:34:04

1

我会用设置的不是List

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

这给了我一个错误: Indexer.java:10:错误:不兼容的类型:ArrayList的不能转换设置 设置 words = new ArrayList (); – juliodesa 2015-04-04 03:54:12

+0

我的错误,它应该是新的HashSet – 2015-04-04 03:58:39

+0

当我这样做时,我仍然得到一个NoSuchElementException。你的回答是否应该解决我的问题,或只是为了改进我的代码? – juliodesa 2015-04-04 21:50:12

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(); 
} 
+0

我试过了,它没有工作。我有一个长的java代码作为我的输入,我的输出是“有一个唯一的单词(s)这些单词是:”后面跟着整个输入。 – juliodesa 2015-04-04 21:56:17

+0

哦,我刚刚解决了NoSuchElementException。使用Set而不是List是@ Pulse9的关键,并提到。该列表将存储每个单词实例;而Set将只存储唯一的实例。 – 2015-04-05 11:24:27

相关问题