我正在编写一个程序,用户在JTextField中输入一堆值,然后是另一个JTextField,然后是另一个,等等。即每个JTextField应包含自己的一组值,我需要一个包含这些值的ArrayLists的ArrayList 。
我的问题是它输出的Arraylist包含一组ArrayLists,所有的值都为null。
我稍后也会添加第三个维度,但如果我可以使用它,这应该相对容易。
以下是我尝试使用的方法的简化测试版本:
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: [[], [], [], [], [], [], [], [], [], [], []]
}
}
答案 0 :(得分:0)
这是因为你不断清除临时arraylist。
在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