简体   繁体   中英

Java ArrayList - Return ArrayList

Basically I have two snippets of code. One calls a function that populates and returns an ArrayList , but I am having some issues. Here are the two codes:

  1. Defining the receiving ArrayList , then catching the returning ArrayList .

    ArrayList agentArray = new ArrayList<>(); agentArray = agentListings(strInput);

  2. Building the ArrayList then returning it.

     public static ArrayList agentListings(String strInput) throws FileNotFoundException { File inputFile = new File(strInput); Scanner in = new Scanner(inputFile); ArrayList<String> agentArray = new ArrayList<>(); while (in.hasNextLine()) { agentArray.add(in.next()); in.next(); in.next(); in.next(); } Collections.sort(agentArray); in.close(); return agentArray; } 

Problem is when I get back to where I am trying to put it into an ArrayList once returned, it seems to work fine. But when I try and write it to a file, it throws this error from this code.

out.write(agentArray.get(1)); 

I am writing to a file with out being a bufferedwriter which works with simple text and such.

Basically I can't figure out how to write the ArrayList "agentArray" to the file. Any obvious errors am I doing?

==============================================

EDIT: Forgot to include the error. When i hover over the out.write(agentArray.get(1)); the agentArray gets underlined in red and the error is

cannot find symbol symbol: varible agentArray
location: class blabla.blabla

If you get an error like this:

cannot find symbol symbol: varible agentArray
location: class blabla.blabla

1) It is a COMPILATION ERROR, so you shouldn't even try to run your program.

2) The error message actually tells you what the problem is ... if you think of it from the perspective the compiler. It is saying this:

"At this point in the code, I looked for an in-scope declaration of agentArray , but I couldn't find one. I didn't try looking for declarations that are not in scope, because they can't be used, and I can't read your mind ..."

Now, we cannot see exactly where the problem is because you've only shown us snippets, and not the code that relates them. But you should be able to figure it out, assuming that you understand that basic Java scoping rules.


When you post error message, you should cut-and-paste the real error messages, not some abridged / baudlerized / mangled version. If you want people to take the time to answer, you should take the time to ask properly.

也许在方法之外声明agentArray时添加一个类型

ArrayList<String> agentArray = new ArrayList<>(); agentArray =agentListings(strInput);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM