2011-07-21 32 views
0

我有一个文本文件包含此:从文件ArrayList中,从数组列表到阵列[]

1 1 0 0 
1 2 0 0 
1 0 1 0 
1 0 2 0 
1 0 0 1 
1 0 0 2 
2 1 0 0 
2 2 0 0 
2 0 1 0 
2 0 2 0 
2 0 0 1 
2 0 0 2 

然后,我把内容在一个ArrayList。结果将与文件中的结果相同。接下来,我想要将数据1加1,并将内容的每一行放在一个数组[] []中,其中数据将按行分隔。 结果将是这样的:

output[0][]={1 1 0 0} 
output[1][]={1 2 0 0} 
output[2][]={1 0 1 0} 
output[3][]={1 0 2 0} 
.... 
.... 
.... 

问题, 我怎么可以把字符串数组列表中成为一个分离的数据? 我的代码在Java

感谢

+2

String#split()方法应该完全按照您的要求进行。它会将你的String分割成一个String []。 –

回答

-1

的问题是:你为什么要使用一个二维数组来存储数据? 用新行解析文件。对于每个新行,将该行添加到数组列表中。 对于数组列表中的每个元素,只需将其添加到数组中即可。我写了一个简单的程序。 它假定您已经解析了文件,并用新行填充了ArrayList。

public static void main(String[] args) { 
    List<String> list = new ArrayList<String>(); 
    list.add("1 0 1 1"); 
    list.add("1 1 1 1"); 
      // etc 

    String[][] array = new String[list.size()][list.size()]; 
    int i = 0; 
    for (String s : list) { 
     stringArray[i++][0] = s; 
    } 

    for (int y = 0 ; y < array.length; y++) { 
     System.out.println(stringArray[y][0]); 
    } 
} 
+0

1.为什么'array' list.size()'的第二维? 2.拆分在哪里? OP表示他需要每条线上的单个数字,而不仅仅是线路本身。 – Thomas

+0

1.它是第n行的大小,这意味着行和列都有相同的大小。我不认为它是正确的? 2.分割我可以使用list.split(“”)?我可以早些时候声明数组吗?我的意思是在主函数之外? – Roubie

1

可以用“公共字符串[]分裂(字符串正则表达式)”的方法,通过指定由您在参数分割字符到阵列分割字符串。 例如String temp =“1 2 3 4”; temp.split(“”); 你将空格在您的情况分为..

1

由于@Benoit已经说过,您可以分割使用String#split(regex)每一行,像这样:

String line = ...; 
String[] parts = line.split("\\s+"); //split on whitespace 

注意,前导空格可能会导致空字符串在开始时,即“1 2 3 4”将导致{"", "1", "2", "3", "4"}。您也可以使用Apache Commons Lang类StringUtils,其split(...)方法负责处理该问题。

还要注意表达\s+这也将分割在多个whitespacem,即, “1       4” 将仍然导致{"1", "2", "3", "4"}

然后,您可以分析各个部分作为整数等

+0

我明白这个工作 – Roubie

0

下面是一些真的简单的代码,做一对夫妇使用扫描仪系列的所有工作,并处理任何数量的每行数字。

编辑:的List<List<Integer>>注意返回类型选择了理智超过int[][]

public static List<List<Integer>> parseIntArrays(InputStream in) { 
    Scanner s = new Scanner(in); 
    List<List<Integer>> list = new ArrayList<List<Integer>>(); 
    while (s.hasNextLine()) { 
     Scanner ns = new Scanner(s.nextLine()); 
     List<Integer> nums = new ArrayList<Integer>(); 
     list.add(nums); 
     while (ns.hasNextInt()) 
      nums.add(ns.nextInt()); 
    } 
    return list; 
} 

这里是为您执行快感一些测试代码:

public static void main(String[] args) { 
    String input = "1 0 0\n1 2 0 0\n1 0 1 0\n1 0 2 0 0 0 1\n1"; 
    List<List<Integer>> result = parseIntArrays(new ByteArrayInputStream(input.getBytes())); 

    for (List<Integer> line : result) 
     System.out.println(line); 
} 

输出:

[1, 0, 0] 
[1, 2, 0, 0] 
[1, 0, 1, 0] 
[1, 0, 2, 0, 0, 0, 1] 
[1] 
+0

boheimian,如果数组内的数字大于4 – Roubie

+0

既然您已经表现出兴趣,我会编码它来处理每行的任意长度的数字列表。查看更新的答案。 – Bohemian