0

I am trying to return an arraylist from this method

 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;
}
}

As I wish to use it in another class. The second class currently looks like this :

public class mean extends reader{

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

}

}

Could someone tell me what am I doing wrong? Whenever I try to return rows I get an error message saying that void methods cannot return a value.

1
  • 3
    The only method declaration I see is your main method. Commented May 21, 2012 at 22:40

1 Answer 1

2

You didn't create a method in your reader object with which to return something from. Create a method signature like the following:

public ArrayList<String[]> getRows() {
    // Rest of your code here.
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I have added in the method as you have suggested but the only return typed it allows me is null otherwise comes up with error messages. Is this what I want? Would appreciate if you could look at updated code.
null is a reference to nothing, which is acceptable when returning objects (which are references to something). However, bear in mind that if you're relying on the existence of the ArrayList, then you would want to throw an exception, rather than return null.
When trying to access the first element of the arraylist in the class mean by newarray[1] I get an error message saying The type of the expression must be an array type but it is resolved to reader. Since I am returning the arraylist, why does it say that?
@user1408525: You have to store the result of your function in the same datatype that its signature calls for - so you'd need to instantiate an ArrayList<String[]> somewhere in main. Also, the first element is at position 0, not 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.