gpt4 book ai didi

java - 为什么我的构造函数不能正常工作?

转载 作者:太空宇宙 更新时间:2023-11-04 14:06:55 24 4
gpt4 key购买 nike

我想要的是我的构造函数过滤出我在文本文件中指定的内容,然后根据过滤后的文本文件使用我的 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 );

}
}

最佳答案

您的问题是您创建的列表是构造函数的局部变量:

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 就可以使用该列表,而无需再次读取该文件(就像当前一样)。

关于java - 为什么我的构造函数不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28777391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com