【问题标题】:Taking input from user and storing (the entire) it into an array with Groovy从用户那里获取输入并使用 Groovy 将其(全部)存储到一个数组中
【发布时间】:2013-12-20 09:59:03
【问题描述】:

好的,我知道我之前问过一个与此非常相似的问题,但我需要知道如何从用户那里获取几个单词并将它们存储到一个数组中并打印出来。我怀疑这将需要一个 for 循环。我试过这段代码,但它不起作用:

System.in.withReader {
    print  'input: '
    def c1 = it.readLine()
    def c2 = it.readLine()
    def c3 = it.readLine()
    def c4 = it.readLine()
    def c5 = it.readLine()
    def c6 = it.readLine()
    def c7 = it.readLine()
    def c8 = it.readLine()
    def c9 = it.readLine()
    def c10 = it.readLine()
    country = [c1,c2,c3,c4,c5,c6,c7,c8,c9,c10]
    assert country.size() == 10
    for(i=0; i<10;i++)
    {

       println country[i]
    }
}

有人有什么想法吗?提前致谢。

【问题讨论】:

    标签: arrays for-loop input groovy


    【解决方案1】:

    你在正确的轨道上。试试这个:

    System.in.withReader {
      def country = []
    
      for (i in 0..9)
        country << it.readLine()
    
      country.each() { println it }
    }
    

    【讨论】:

    • groovy 中是否有一个函数可以颠倒数组中元素的打印顺序?
    • 当然,您可以使用 Groovy List#reverse 方法。 country.reverse().each() { println it }
    • 我会说绝对!在 JVM 上编写、简洁和运行非常简单。在我工作的地方,我们经常使用 Groovy(和 Grails)。
    • System.in.withReader { r -&gt; country = (1..10).collect { r.readLine() } } 将是另一种方式
    • 代码:country.reverse().each() { println it } 反向打印数组失败。输入 10 个元素后,我得到一个退出代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2011-11-05
    相关资源
    最近更新 更多