我的程序存在问题,涉及数组列表、缓冲读取器、方法以及对 Java 工作原理的总体遗忘
我在执行一整天的程序时遇到了困难。我正在尝试读取一个文本文件并一次读取每一行。取出该行并创建该行单词的数组列表。然后使用数组列表的索引来定义术语。
public class PCB {
public static void main(String arg[]) {
read();
}
public static ArrayList read() {
BufferedReader inputStream = null;
ArrayList<String> tokens = new ArrayList<String>();
try {
inputStream = new BufferedReader(new FileReader("processes1.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
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 am having difficulties with a program that I have been working on all day. I am trying to read a text file and read each line one at a time. Take that line and make an arraylist of the words of the line. then using the index of the arraylist define terms with it.
public class PCB {
public static void main(String arg[]) {
read();
}
public static ArrayList read() {
BufferedReader inputStream = null;
ArrayList<String> tokens = new ArrayList<String>();
try {
inputStream = new BufferedReader(new FileReader("processes1.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
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;
}
}
The error I am getting is it only reads the first line. What am I doing wrong?
Thank you so much in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你有“返回令牌”;在你的 while 循环中。看来提前返回会有效地切断第一线的处理。
You have "return tokens;" in your while loop. Seems like that early return would effectively cut off processing on the first line.
尝试将循环更改为以下内容。请注意我如何移动 return 语句。
编辑:如果您想读取整个文件并将每行的标记存储在单独的数组中,那么您可以创建一个
ArrayList
的ArrayList
>。注意:我的 Java 生锈了。
Try changing your loop to the following. Note how I moved the return statement.
Edit: If you want to read the entire file and store the tokens of each line in a seperate array, then you could create an
ArrayList
ofArrayList
.Note: My Java is rusty.
简化为......
创建文件中所有行上的所有标记的列表(如果这是您想要的)。
Simplify to this ...
... creates a list of all tokens on all lines in the file (if that is what you want).