【发布时间】:2014-08-17 23:44:06
【问题描述】:
我想知道如何将以下数据拆分为多个列表。这是我的输入(来自文本文件,此处重新创建了示例):
aaaa bbbb cccc,ccc,cccc
aaaa-- bbbb
aaaa bbbb cccc-
aaaa bbbb cccc,ccc
aaaa-
aaaa bbbb ccc,cccc,cccc
分隔文本的每个部分是一个空格。我需要制作的代码应该创建三个列表,由文本文件中每个条目的 a、b 和 c 组组成,相对于每一行,同时忽略任何带有“-”的行。所以,我的 3 个数组应该填充如下:
Array1: aaaa, aaaa, aaaa
Array2: bbbb, bbbb, bbbb
Array3: (cccc,ccc,cccc),(cccc,ccc),(ccc,cccc,cccc)
添加了括号以显示第三个数组应包含所有列出的 c 值 a、b 和 c 都包含从文本文件导入的字符串。到目前为止,这是我的代码:
import java.util.*;
import java.io.*;
public class SEED{
public static void main (String [] args){
try{
BufferedReader in = new BufferedReader(new FileReader("Curated.txt"));
String temp;
String dash = "-";
int x = 0;
List<String> list = new ArrayList<String>();
List<String> names = new ArrayList<String>();
List<String> syn = new ArrayList<String>();
List<String> id = new ArrayList<String>();
while((temp = in.readLine()) != null){
if(!(temp.contains(dash))){
list.add(temp);
if(temp.contains(" ")){
String [] temp2 = temp.split(" ");
names.add(temp2[0]);
syn.add(temp2[1]);
id.add(temp2[2]);
}else{
System.out.println(temp);
}//Close if
System.out.println(names.get(x));
System.out.println(syn.get(x));
System.out.println(id.get(x));
x++;
}//Close if
}//Close while
}catch (Exception e){
e.printStackTrace();
System.exit(99);
}//Close try
}//Close main
}//Close class
但我的输出总是:什么都没有。如何正确地将这些值保存到 3 个单独的 Arrays 或 ArrayLists?
【问题讨论】:
-
好吧,我会迭代所有元素,我会使用很多 if 和 string 的 contains() 来做到这一点。
-
谢谢桑托斯先生,我找到了以下错误:java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.rangeCheck(ArrayList.java:604 ) 在 java.util.ArrayList.get(ArrayList.java:382) 在 SEED.main(SEED.java:39)
-
我也不会在您的异常处理中使用 System.exit(99)
标签: java arrays file text arraylist