0

私は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 
        }

    }
}

リストを印刷することはできますが、プログラムでリストのリストを使用する方法がわかりません(他の操作を実行するため)。誰かがここで私を助けてくれますか?

4

1 に答える 1

1

input.each必要なのは、行の各項目をもう一度繰り返すことだけです。それが未知の深さのコレクションである場合は、再帰的な方法に固執する必要があります。

inc(少なくともスニペットでは)必要ないため、小さな変更を加えて削除しました。

fname = """1 
2 3
4 5 6
7 8 9 10"""

def input = []
fname.eachLine { line->
  def array = line.split(" ")
  def list = []
  for (item in array)  {
      list.add item.toInteger()
  }
  input.add list 
}

input.each { line ->
   print "items in line: "
   for (item in line) {
     print "$item "
   }
   println ""
}

プリント:

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

それは単純な反復です。@Timの提案を使用して、Groovyでより慣用的なものにすることができます:-)

于 2013-03-27T14:05:10.123 に答える