[英]Why is my Constructor not working properly?
我想要的是構造函數可以過濾掉我在文本文件中指定的內容,然后基於過濾后的文本文件使用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
可以使用該列表,而不必再次讀取該文件(如當前一樣)。
你的
ArrayList<String> lst = new ArrayList<String>();
在構造函數中聲明和初始化。 它是一個局部變量,而不是實例變量。 因此,即使您的邏輯運行正常,您也無法訪問它。 您可以將聲明部分移到構造函數之外。
ArrayList<String> lst;
public TextProcessorImpl(String filename) {
lst = new ArrayList<String>();
....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.