2011-07-25 40 views
0

我有这个数组列表,我想把数据放在array.but但我有问题来分离数据。 的ArrayList DATA_LIST:在java中的数组的字符串

g e r m a n y 
a u s t r a l i a 
n e w z e a l a n d 
e n g l a n d 
c o s t a r i c a 
p h i l i p i n a 
m y a n m a r 
t h a i l a n d 

注:每个字母都是用空格分开。 我想分开国家的名称,以成为单独的字母,如 德国成为我的朋友 我打算将arraylist转换为2d array.so输出变成这样: String [] [] country;

country[0][0]=g 
country[0][1]=e 
country[0][2]=r 
country[0][3]=m 
country[0][4]=a 
country[0][5]=n 
country[0][6]=y 

country[1][0]=a 
country[1][1]=u 
country[1][2]=s 
country[1][3]=t 
country[1][4]=r 
country[1][5]=a 
country[1][6]=l 
country[1][7]=i 
country[1][8]=a 

任何人都可以帮助我吗?

+0

我们的原始ArrayList是String的数组列表吗? –

回答

0

如果你的ArrayList是这样的:

List<String> countries = Arrays.asList("g e r m a n y", "a u s t r a l i a", "n e w z e a l a n d", 
    "e n g l a n d", "c o s t a r i c a", "p h i l i p i n a", "m y a n m a r", "t h a i l a n d"); 

然后你就可以创建你的字符数组是这样的:

String[][] countryLetters = new String[countries.size()][]; 
for (int i = 0; i < countries.size(); i++) { 
    String country = countries.get(i); 
    countryLetters[i] = country.split(" "); 
} 
// test output 
for (String[] c : countryLetters) { 
    System.out.println(Arrays.toString(c)); 
} 

测试输出是

[g, e, r, m, a, n, y] 
[a, u, s, t, r, a, l, i, a] 
[n, e, w, z, e, a, l, a, n, d] 
[e, n, g, l, a, n, d] 
[c, o, s, t, a, r, i, c, a] 
[p, h, i, l, i, p, i, n, a] 
[m, y, a, n, m, a, r] 
[t, h, a, i, l, a, n, d] 
+0

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0 – Roubie

+0

它现在工作吗?代码在这里运行。 – migu

+0

仍然不能run.with d相同的错误 – Roubie

1

使用String类的toCharArray()方法。

0
ArrayList<String> orig = new ArrayList<String>(); 
orig.add("G e r m a n y"); 
orig.add("A u s t r a l i a"); 

String[][] newArray = new String[orig.size()][]; 
int i = 0; 
for(String s : orig) 
    newArray[i++] = s.split(" "); 
+0

如果你需要循环中的索引,我通常会避免每个循环。 (其中包括限制“临时”变量的范围)。 – aioobe

+0

此解决方案不处理字母之间的空格。 – migu

0
String a = "germany"; 
    String b = "india"; 
    char[] ar = a.toCharArray(); 
    char[] br = b.toCharArray(); 
    char [][] td = new char[2][2]; 
    td[0] = ar; 
    td[1] = br; 
    System.out.println(td); 
    System.out.println(td[0][0]+""+td[0][1]+""+td[0][2]+""+td[0][3]+""+td[0][4]+""+td[0][5]+""+td[0][6]); 
+0

这是什么?我不明白 – Roubie