Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Collections Groovy列表或2D数组_Collections_Groovy - Fatal编程技术网

Collections Groovy列表或2D数组

Collections Groovy列表或2D数组,collections,groovy,Collections,Groovy,我是groovy新手,我正在编写一个程序,用于从具有以下格式的输入文件中读取数字 1 2 3 4 5 6 7 8 9 10 我希望将它们存储在2D阵列中,我将如何实现它 到目前为止,我已经为read方法编写了以下代码 private read(fileName){ def count = 0 def fname = new File(fileName) if (!fname.exists()) println "File Not Found"

我是groovy新手,我正在编写一个程序,用于从具有以下格式的输入文件中读取数字

1 
2 3
4 5 6
7 8 9 10
我希望将它们存储在2D阵列中,我将如何实现它

到目前为止,我已经为read方法编写了以下代码

private read(fileName){
    def count = 0
    def fname = new File(fileName)

    if (!fname.exists())
        println "File Not Found"

    else{
        def input = []
        def inc = 0
        fname.eachLine {line->
            def arr = line.split(" ")
            def list = []
            for (i in 1..arr.length-1)  {
                list.add(arr[i].toInteger())
            }
            input.add(list)//not sure if this is correct
            inc++
        }
        input.each {
             print it
                //not sure how to reference the list 
        }

    }
}

我能够打印列表,但我不确定如何在程序中使用列表列表(用于对其执行其他操作)。有人能帮我吗?

输入中。您只需在行中的每个项目中再次迭代。如果它是一个未知深度的集合,那么您需要坚持使用递归方法

做了一个小改动并删除了
inc
,因为它不需要(至少在代码段中):

印刷品:

items in line: 1 
items in line: 2 3 
items in line: 4 5 6 
items in line: 7 8 9 10 

这就是简单的迭代。您可以使用@Tim的建议使它在Groovy中更加惯用:-)

您可以将所有
fname.eachLine
块更改为
fname.eachLine{line->输入。对于第二部分,我的意思是如何引用列表来执行数组操作?
items in line: 1 
items in line: 2 3 
items in line: 4 5 6 
items in line: 7 8 9 10