How to return arraylist from a method


I need help. For this particular method. I am trying to get him to return the arraylist that I designated.

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

+5
source share
4 answers

At the very end you do return tokens, but this variable was defined by INSIDE in the try block, so it is not available outside of it. You must add:

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

at the top of your method, just under BufferedReader.

+10
source

Try returning an ArrayList, which is a more suitable return type in this case. Generic types are not related to each other in the way your example uses them.

0
source

, . read() ?

0

:

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;

    }}
0

All Articles