我想要的是构造函数过滤掉我在文本文件中指定的内容,然后基于过滤后的文本文件使用getLongestWord方法。我试图使包含0-9的单词被忽略,并且在存储之前删除单词中的所有标点符号。纯粹是标点符号的单词将被忽略。构造函数返回后,新实例将具有进行分析所需的所有信息。该文件将不再需要。
public class TextProcessorImpl implements TextProcessor {
private String filename;
public TextProcessorImpl(String filename) {
this.filename = filename;
String current;
Scanner scan = TextReader.openFile(filename);
ArrayList<String> lst = new ArrayList<String>();
while (scan.hasNext()) {
current = scan.next();
if (current.matches(".*[0-9].*")) {
}
else {
current = current.replaceAll("\\p{Punct}+", "");
if (current.isEmpty()) {
}
else {
lst.add(current);
}
}
}
}
@Override
public Collection<String> getLongestWords() {
String longestWord = "";
String current;
Scanner scan = TextReader.openFile(filename); // Generate scanner
ArrayList<String> lst = new ArrayList<String>(); //create array list
while (scan.hasNext()) { //while the text has a next word in it
current = scan.next(); //set current to that next word
if (current.length() > longestWord.length()) { //if the current word length is greater than the longest word length
longestWord = current; //set the new longest word to current
lst.clear(); //clear the previous array
lst.add(longestWord); //add the new longest word
}
else if( current.length() == longestWord.length()) { //else if the current word length = the longest word length
if (!lst.contains(current)) {
lst.add(current); //add the current word to the array
}
}
}return lst;
}
主程序:
public class TextAnalysis {
/**
* Get a file name from the command line and ask a TextProcessor
* to analyze it.
*
* @param args a single-element array containing the file name
*/
public static void main( String[] args ) {
if ( args.length != 1 ) {
System.err.println( "Usage: java TextProcessor file" );
System.exit( 2 );
}
TextProcessor textProc = new TextProcessorImpl( args[ 0 ] );
Collection< String > longestWords = textProc.getLongestWords();
System.out.println( "Longest words: " + longestWords );
}
}
您的问题是,您创建的列表是consructor的局部变量:
ArrayList<String> lst = new ArrayList<String>();
因此,构造函数收集的任何数据都不会存储在实例中。您应该使该lst
成员成为班上的一员。
public class TextProcessorImpl implements TextProcessor {
private String filename;
private ArrayList<String> lst = new ArrayList<String>();
public TextProcessorImpl(String filename) {
this.filename = filename;
String current;
Scanner scan = TextReader.openFile(filename);
...
然后,您getLongestWords
可以使用该列表,而不必再次读取文件(就像当前一样)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句