2017-04-23 53 views
0

我写了用户在JTextField中输入一串值的程序,然后又JTextField中,然后又等。也就是说,每个JTextField中应包含它自己的一套值,我需要一个ArrayList包含这些值的ArrayLists。转换一组字符串被解析到一个多维数组彩车

我的问题是,它的输出包含一系列的ArrayLists的ArrayList,所有的人的价值观是空的。

我稍后也将被添加第三维它,但应该是比较容易的,如果我能得到这个工作。

下面是方法,我尝试使用的简化版本的测试:

import java.util.ArrayList; 
import java.util.Arrays; 

public class Test { 
    public static void main(String args[]) { 

    ArrayList<Float> temp = new ArrayList<>();         //holds each float parsed from an ArrayList of strings 
    ArrayList<ArrayList<Float>> output = new ArrayList<>();      //holds each set of floats 
    ArrayList<String> items;             //the string before its parsed into floats 

    String s = "1,2,3,4,5,6";             //testing values 

    for (int i = 0; i <= 10; i++) {            //10 is a random testing number 
     //In the real version s changes here 
     items = new ArrayList<String>(Arrays.asList(s.split("\\s*,\\s*"))); //split strings by comma accounting for the possibility of a space 

     for (String b : items) {            //parse each number in the form of a string into a float, round it, and add it to temp 
      temp.add((float)((long)Math.round(Float.valueOf(b)*10000))/10000); 
     } //End parsing loop 

     output.add(temp);              //put temp in output 
     temp.clear();               //clear temp 
    } //End primary loop 

    System.out.println(output);             //output: [[], [], [], [], [], [], [], [], [], [], []] 
} 

}

+1

什么是你的问题? –

+0

我不知道为什么它输出一个空数组的数组。 –

+1

你为什么不调试它并亲自看看? –

回答

0

这是因为你一直在清理临时数组列表。

在for循环中创建ArrayList<Float> temp = new ArrayList<>();并且不清除它。

for (int i = 0; i <= 10; i++) {            //10 is a random testing number 
    //In the real version s changes here 
    items = new ArrayList<String>(Arrays.asList(s.split("\\s*,\\s*"))); //split strings by comma accounting for the possibility of a space 

    // create this inside so you have a new one for each inner list 
    ArrayList<Float> temp = new ArrayList<>(); 
    for (String b : items) {            //parse each number in the form of a string into a float, round it, and add it to temp 
     temp.add((float)((long)Math.round(Float.valueOf(b)*10000))/10000); 
    } //End parsing loop 

    output.add(temp); 

    // don't clear 
    //temp.clear();               //clear temp 
} //End primary loop 
相关问题