【问题标题】:Returning arraylist and using in different class返回arraylist并在不同的类中使用
【发布时间】:2012-05-28 10:40:40
【问题描述】:

我正在尝试从此方法返回一个数组列表

 import java.io.*;
import java.util.*;
/** The class reader read the file 2RainfallDataLanc.txt and stores is as an ArrayList. 
 * It also parses the variables within the file by white spaces, making variables accessible.
 *
 */
public class reader {

    public ArrayList<String[]> getRows(){

    try {
            BufferedReader reader = new BufferedReader(new FileReader("2RainfallDataLanc.txt"));
            String line = null;
            ArrayList<String[]> rows = new ArrayList<String[]>();

            while((line=reader.readLine())!=null) 
            {String[] row = line.split("\\s+");
            rows.add(row);

                }
            for (String[] row : rows) {
                System.out.println(Arrays.toString(row));
                return rows;
                }   

} catch (IOException e) {
}
    return null;
}
}

因为我希望在另一个课程中使用它。第二类目前看起来像这样:

public class mean extends reader{

public static void main(String[] args) {
    reader newarray = new reader();

}

}

谁能告诉我我做错了什么?每当我尝试返回行时,我都会收到一条错误消息,指出 void 方法无法返回值。

【问题讨论】:

  • 我看到的唯一方法声明是你的main 方法。

标签: java arraylist return


【解决方案1】:

您没有在您的 reader 对象中创建用于返回某些内容的方法。创建一个方法签名,如下所示:

public ArrayList<String[]> getRows() {
    // Rest of your code here.
}

【讨论】:

  • 嗨,我已经按照您的建议添加了方法,但它允许我输入的唯一返回是 null ,否则会出现错误消息。这是我想要的吗?如果您能查看更新的代码,将不胜感激。
  • null 是对空的引用,这在返回对象(即对某物的引用)时是可以接受的。但是,请记住,如果您依赖 ArrayList 的存在,那么您可能希望throw 异常,而不是返回 null。
  • 当试图通过 newarray[1] 访问类中数组列表的第一个元素时,我收到一条错误消息,指出表达式的类型必须是数组类型,但它已解析给读者。既然我是返回arraylist,为什么会这样说呢?
  • @user1408525:您必须将函数的结果存储在其签名所要求的相同数据类型中——因此您需要在 main 中的某处实例化 ArrayList&lt;String[]&gt;。此外,第一个元素位于位置 0,而不是 1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 2015-02-02
  • 1970-01-01
相关资源
最近更新 更多