Я хочу, чтобы мой конструктор отфильтровал то, что я указал в текстовом файле, а затем использовал мой метод 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 );
}
}
2 ответа
Ваша проблема в том, что созданный вами список является локальной переменной конструктора:
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
может использовать этот список без необходимости повторного чтения файла (как это происходит сейчас).
Ваш
ArrayList<String> lst = new ArrayList<String>();
Объявляется и инициализируется в конструкторе. Это локальная переменная, а не переменная экземпляра. Поэтому вы не можете получить к нему доступ, даже если ваша логика работает нормально. Вы можете переместить часть объявления за пределы конструктора.
ArrayList<String> lst;
public TextProcessorImpl(String filename) {
lst = new ArrayList<String>();
....
}
Похожие вопросы
Новые вопросы
java
Java — это высокоуровневый объектно-ориентированный язык программирования. Используйте этот тег, если у вас возникли проблемы с использованием или пониманием самого языка. Этот тег часто используется вместе с другими тегами для библиотек и/или фреймворков, используемых разработчиками Java.