2017-04-23 95 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 
相關問題