所以我必须创建这个对象DocumentAnalyzer,然后在其他函数中,例如getUniqueWords,我必须能够获取其中保存的文件的内容,并对内容进行排序。为了获得唯一的单词,我将使用 Set
,因为它不能有重复项。
对象:
public DocumentAnalyzer(String filename) throws FileNotFoundException
{
List<String> records = new ArrayList<String>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null)
{
records.add(line);
}
reader.close();
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
return;
}
System.out.print(records);
}
public Set<String> getAllWords(?????)
{
Set<String> set = new HashSet<>(values);
for (String value : set)
System.out.printf("%s", value);
return set;
}
如何才能在调用函数时使用 DocumentAnalyzer 中的信息?我知道它与参数有关,所以我必须转换一些东西吗?我只是忽略了它实际上很简单吗? 我已经为此苦恼了好几个小时了
最佳答案
您发布的代码可能位于 class
中声明,如:
public class DocumentAnalyzer {
// your code here
}
您当前的问题是List<String> records
是构造函数的局部变量。
您需要的是将信息存储为此类的字段(也称为属性),而不是将变量声明保留在构造函数中:
public class DocumentAnalyzer {
private List<String> records;
// your code here
}
然后,在构造函数中使用该字段而不是局部变量,方法是替换:
List<String> records = new ArrayList<String>();
作者:
records = new ArrayList<String>();
现在您的 getAllWords()
不需要任何参数方法,因为您只需使用 records
,可以从那里访问。
关于java - 从对象获取信息(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28328575/