将文本文件中的唯一单词添加到 ArrayList 的程序 [英] Program that adds unique words from text file to an ArrayList
问题描述
我正在编写一个程序,该程序读取包含多行文本的文本文件并将唯一的单词添加到 ArrayList.然后,我需要对这个 ArrayList 进行排序并打印它.我的输入是:
I am writing a program that reads a text file with multiple lines of text and adds unique words to an ArrayList. Then, I need to sort this ArrayList and print it. My input is:
你好我的
我的名字是
Hello my
my name is
Java.
我最初认为我的问题是一旦扫描器遇到一个已经在 ArrayList 中的单词,它就会停止.但是,在更改我的输入后,我不知道我的问题是什么了.我的输出现在是:
I originally thought my problem was that once the Scanner hit a word that is already in the ArrayList, it stopped. But, after changing my input, I have no idea what my problem is anymore. My output is now:
有2个独特的词
这些话是:
是
我的
There are 2 unique word(s)
These words are:
is
my
我需要我的输出:
有5个独特的词
这些话是:
你好
爪哇
是
我的
姓名
There are 5 unique word(s)
These words are:
Hello
Java
is
my
name
这是我的代码:
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"));
fileScanner.useDelimiter("[^A-Za-z0-9]");
ArrayList<String> words = new ArrayList<String>();
while (fileScanner.hasNext())
{
if (!words.contains(fileScanner.next()) && (fileScanner.hasNext()))
{
words.add(fileScanner.next());
}
}
Collections.sort(words);
System.out.println("There are " + words.size() + " unique word(s)");
System.out.println("These words are:");
for (Iterator<String> it = words.iterator(); it.hasNext();)
{
String f = it.next();
System.out.println(f);
}
fileScanner.close();
}
}
我做错了什么?
推荐答案
您重复使用了 next()
,超过了它应该使用的次数.在变量中收集 next()
调用的值并使用它.例如
You're using the next()
repeatedly, more than it should be used. Collect the value of the next()
call in a variable and use that instead. E.g.
while (fileScanner.hasNext())
{
String nextWord = fileScanner.next();
if (!words.contains(nextWord))
{
words.add(nextWord);
}
}
这篇关于将文本文件中的唯一单词添加到 ArrayList 的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!