問題描述
我正在做一個自學練習,以幫助我更多地了解 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!