如何从方法返回数组列表
我需要帮助。对于这个具体的方法。我试图让它返回我标记化的数组列表。
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;
}
我做错了什么?!
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?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最后,您正在执行
返回标记
,但该变量是在 try 块内部定义的,因此无法在其外部访问它。您应该添加:ArrayList; tokens = new ArrayList();
到方法顶部,就在 BufferedReader 下方。
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.
尝试返回 ArrayList,在这种情况下这是更合适的返回类型。泛型类型并不像您的示例使用它们的方式那样相互关联。
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.
这可能是您的 main 方法中某处的错误。您是否实例化该类并在其上调用方法 read() ?
It is probably an error in your main method somewhere. Are you instantiating the class and calling the method read() on it?
试试这个:
Try this: