【问题标题】:Reading Strings from a file and putting them into an array with Groovy从文件中读取字符串并使用 Groovy 将它们放入数组中
【发布时间】:2013-12-18 21:25:17
【问题描述】:

请原谅这个新手问题,但我正在学习如何使用 Groovy 做一些基本的事情。我需要知道如何从文件(让我们称之为文件 list.txt)或从键盘读取单词并将它们存储到字符串数组(假设是大小为 10 的数组)中,然后将它们打印出来。我该怎么做呢?我在这件事上找到的例子对我来说不清楚。

【问题讨论】:

标签: arrays input groovy output


【解决方案1】:

怎么样:

def words = []
new File( 'words.txt' ).eachLine { line ->
    words << line
}

// print them out
words.each {
    println it
}

【讨论】:

  • @Inquirer21 it 是使用闭包时的关键字。 it 是迭代的当前对象。您可以重命名it,就像在第一部分中所做的那样,将其重命名为line
  • @Inquirer21 it 是对闭包中隐式对象的引用;在这种情况下,您可以使用 it 引用 words 中的元素
  • 哦,好的,谢谢。有谁知道如何将键盘输入读入字符串数组?
  • 我想我需要在另一个问题中问这个问题。
【解决方案2】:

其实这很容易:

String[] words = new File('words.txt')

或者,您可以使用:

def words = new File('words.txt') as String[]

【讨论】:

  • 请注意,从您最初的问题开始,这假设您每行有一个单词。
猜你喜欢
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-04-04
  • 2018-04-25
相关资源
最近更新 更多