Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?!

like image 498
Luron Avatar asked Sep 20 '10 00:09

Luron


1 Answers

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.

like image 127
Mitch Dempsey Avatar answered Sep 29 '22 19:09

Mitch Dempsey