java - 从对象获取信息(JAVA)

标签 java methods parameters set hashset

所以我必须创建这个对象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/

相关文章:

azure - 检查逻辑应用 HTTP 请求中是否存在查询字符串

javascript - 使用 setTimeout 时将值传递给 javascript 中的函数

Java 内存、按值传递、按引用传递

java - Akka Scala 和 Java 的区别

java - 我的 JPA/Hibernate 自定义类型有什么问题?

java - 使用 Maven 程序集插件包含特定依赖项

Java:在跳过中间继承的父类(super class)时调用基父类(super class)方法

java - 我怎样才能在其他方法中使用方法?

C# 方法的最大值?即尺寸(int x < 40,int y < 80)?

ruby-on-rails - 如何在 RSpec Rails 请求规范中传递额外参数