问题描述
我正在做一个自学练习,以帮助我更多地了解 Java,但我被这个问题困住了.我有以下 txt 文件:
I am doing a self learning exercise to help me understand more about Java, but I am stuck at this question. I have the following txt file:
Name Hobby
Susy eat fish
Anna gardening
Billy bowling with friends
注意:姓名和爱好用制表符隔开
阅读所有行并将其放入 arraylist(name,hobby) 的最佳方法是什么.棘手的部分是
What is the best way to read all the line and put it in arraylist(name,hobby). The tricky part is that
eat fish or bowling with friends
有空格,它必须放在一个数组下,显然我无法对其进行硬编码.这是我当前的代码:
has white spaces and it must be put under one array and obviously I cannot hardcode it. Here is my current code:
public void openFile(){
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
// use DataInputStream to read binary NOT text
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> hobbies = new ArrayList<String>();
String lineJustFetched;
while ((lineJustFetched = br.readLine()) != null) {
String[] tokens = lineJustFetched.split(" ");
我遇到了一个错误:
java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
我怀疑计算索引在选项卡上不是很有用.有什么想法吗?
I suspect counting the index is not very useful on a tab. Any idea?
推荐答案
好的,你需要按照下图的方法进行:
Alright, you need to do the recipe shown below:
- 创建一个
BufferedReader
- 创建一个
ArrayList
- 开始将数据读取到名为
lineJustFetched
的String
变量中. - 调用
lineJustFetched.split(" ");
分割 - 迭代生成的
String[]
.检查你要进入ArrayList
的token是否不是""
- 如果没有,则将单词添加到
ArrayList
String
- Create a
BufferedReader
- Create an
ArrayList<String>
- Start reading data into a
String
variable namedlineJustFetched
. - Split the
String
by callinglineJustFetched.split(" ");
- Iterate over the
String[]
produced. Check if the token you want to enter into theArrayList
is not""
- If not, add the word to the
ArrayList
您指定需要根据
值进行拆分,这样空格就不会成为问题.
You specify that you need to split based on
values so white spaces won't be an issue.
SSCCE
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class WordsInArray {
public static void main(String[] args) {
try{
BufferedReader buf = new BufferedReader(new FileReader("/home/little/Downloads/test"));
ArrayList<String> words = new ArrayList<>();
String lineJustFetched = null;
String[] wordsArray;
while(true){
lineJustFetched = buf.readLine();
if(lineJustFetched == null){
break;
}else{
wordsArray = lineJustFetched.split(" ");
for(String each : wordsArray){
if(!"".equals(each)){
words.add(each);
}
}
}
}
for(String each : words){
System.out.println(each);
}
buf.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
输出
John
likes to play tennis
Sherlock
likes to solve crime
这篇关于读取由制表符分隔的文件并将单词放入 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!