我是一名自学者,正在进行有关Java的练习,但我卡在了这个问题上。我有以下txt文件:
Name Hobby
Susy eat fish
Anna gardening
Billy bowling with friends
注意:名字和爱好之间用制表符分隔 最佳方法是读取所有行并将其放入arraylist(name,hobby)中。棘手的部分是:
eat fish or bowling with friends
有空格的字符串必须放在一个数组中,但我无法硬编码。以下是我的当前代码:
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(" \t");
我遇到了一个错误:
java.lang.StringIndexOutOfBoundsException: 字符串索引超出范围:-1
我怀疑在制表符上计算索引并不是很有用。有什么想法吗?