如何将jTextArea扫描到arraylist或2d数组

时间:2015-01-11 23:52:08

标签: java arrays arraylist

我有一个jTextArea有这个值[1,3,5,5,5,6],[5,1,4,3,3,3],[3,5,6,5,5,4]

我的问题是如何将此jTextArea中的数据放入二维数组或Arraylist?

我的代码:

public void toList(JTextArea textArea){

    ArrayList<String>arrList = new ArrayList<>(Arrays.asList(jTextArea1.getText())) ;   
    arrList.stream().forEach((jh) -> {
       System.out.println(jh);
    });
} 

但它没有为输出返回任何内容。

1 个答案:

答案 0 :(得分:0)

您需要将String拆分为单个组件

[1,3,5,5,5,6]
[5,1,4,3,3,3] 
[3,5,6,5,5,4]

然后将每个“块”分成一系列单独的数字

1
3
5
5
5
6

等等,例如......

    // Test value
    String text = "[1,3,5,5,5,6],[5,1,4,3,3,3],[3,5,6,5,5,4]";
    // Break down the outter blocks [...]
    String[] blocks = text.split("],");
    // Build the array....
    String[][] blocksArray = new String[blocks.length][];
    for (int index = 0; index < blocks.length; index++) {
        // Get the next block [...]
        String block = blocks[index];
        // Remove the brackets [ and ]
        block = block.replace("[", "").replace("]", "");
        // Break the numbers apart....
        String[] elements = block.split(",");
        // Apply the numbers to the block array
        blocksArray[index] = elements;
    }

使用...

    for (String[] block : blocksArray) {
        System.out.println(Arrays.toString(block));
    }

我明白了......

[1, 3, 5, 5, 5, 6]
[5, 1, 4, 3, 3, 3]
[3, 5, 6, 5, 5, 4]

注意Arrays.toString正在添加[,以及]