我有一个程序可以导入一个字符串文件,解析它以获得正确的单词,然后过滤掉并打印出唯一的单词。我已经设置了一个类来导入.txt文件并将这些单词放入ArrayList:
for
}
和Main(),过滤方法和打印:
public class RawText
{
ArrayList<String> allWords = new ArrayList<String>(); //raw list of words
/**
* This method reads strings from file, filters for only upper/lowercase strings and adds to allWords
* @throws IOException
* @params filename: a string filename
*/
public void add(String filename) throws IOException
{
File inFile = new File(filename); //inst. file import for raw
Scanner read = new Scanner(inFile); //inst. scanner object
while (read.hasNext()) //reads until end of text
{
String word = read.next(); //scanner reads next complete string
word = word.replaceAll("[^a-zA-Z", ""); //filters out non-alphabet chars
allWords.add(word); //adds 'stripped-down' string to list
}
read.close();
}
我需要知道是否有更合适/有效的方法来设置我的类,以及是否有原因使uniquewords.add()在removeRepeats()方法的第二行中不起作用。< / p>
谢谢。
答案 0 :(得分:1)
你的一些问题:
uniqueWords.add(0) = allWords.get(0);
这里,您要向字符串的ArrayList添加一个整数0。你可能想要:
uniqueWords.add(allWords.get(0));
此外,稍后您将字符串与==:
进行比较if (allWords.get(i) == uniqueWords.get(j))
==仅应在比较基元数据类型时使用。要比较字符串,请使用方法equals(String)或equalsIgnoreCase(String):
if (allWords.get(i).equalsIgnoreCase(uniqueWords.get(j))