Luron
Luron

Reputation: 1187

How to return an arraylist from a method


I need help. For this specific method. I am trying to get it to return an arraylist that I tokenized.

public ArrayList read (){

  BufferedReader inputStream = null;
  try {
    inputStream = new BufferedReader(new FileReader("processes1.txt"));
    String l;
    while ((l = inputStream.readLine()) != null) {

      ArrayList<String> tokens = new ArrayList<String>();

      Scanner tokenize = new Scanner(l);
      while (tokenize.hasNext()) {
        tokens.add(tokenize.next());
      }
      return tokens;
    }
  } catch(IOException ioe){
    ArrayList<String> nothing = new ArrayList<String>();
    nothing.add("error1");
    System.out.println("error");
    //return nothing;
  }
  return tokens;
}

What am I doing wrong?!

Upvotes: 5

Views: 46526

Answers (4)

Eternal_Explorer
Eternal_Explorer

Reputation: 1145

Try this:

public ArrayList read (){

          File text = new File("processes1.txt");

              ArrayList<String> tokens = new ArrayList<String>();

              Scanner tokenize;
            try {
                tokenize = new Scanner(text);
                while (tokenize.hasNext()) {

                      tokens.add(tokenize.next());
                  }

                }

            catch(IOException ioe){
                ArrayList<String> nothing = new ArrayList<String>();
                nothing.add("error1");
                System.out.println("error");
                //return nothing;
              }
             return tokens;

    }}

Upvotes: 0

venky
venky

Reputation: 153

It is probably an error in your main method somewhere. Are you instantiating the class and calling the method read() on it?

Upvotes: 0

Aurojit Panda
Aurojit Panda

Reputation: 909

Try returning ArrayList which is the more appropriate return type in this case. Generic types aren't related to each other the way your example seems to be using them.

Upvotes: 0

Mitch Dempsey
Mitch Dempsey

Reputation: 39889

At the very end you are doing return tokens but that variable was defined INSIDE the try block, so it is not accessible outside of it. You should add:

ArrayList<String> tokens = new ArrayList<String>();

to the top of your method, just under the BufferedReader.

Upvotes: 10

Related Questions