java - Groovy "java.lang.Integer.readLine() is applicable for argument types: () values: []"错误

标签 java groovy io

我正在尝试编写一段简短的代码,该代码将从控制台读取几行。这是我的代码:

System.in.withReader {
    int a = it.readLine() as int
    (1..a).each {
        int b = it.readLine() as int
        def sum = 0
        (0..(b-1)).each {d ->
            sum+=(-1)^d/(2*d+1)
        }
        println sum/4
    }
}

这是来自控制台的输入:

1
20

这是我得到的错误:

java.lang.Integer.readLine() is applicable for argument types: () values: []

我有一种感觉,Groovy 无法从控制台获取输入。当我尝试调试时,它不允许我在控制台中输入任何内容。

最佳答案

您的第一个 each 会遮蔽 withReader 中的 it:

System.in.withReader { /* implicit it */
    int a = it.readLine() as int
    (1..a).each { /* implicit it */
        int b = it.readLine() as int // this `it` now is an int from (1..a)

给内部的it一个名称(就像你稍后对d所做的那样),原始的it将保留为读取器。为了进一步解决这个问题,您甚至可能想为读者提供自己的变量名称。

关于java - Groovy "java.lang.Integer.readLine() is applicable for argument types: () values: []"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29147204/

相关文章:

java - 毫秒到 LocalDateTime

java - 创建形状并在控制台上显示它们的程序

grails - 将 src/groovy 类中的值设置为域类属性

java - 了解 gradle 多项目构建

Jenkins:可以将注释添加到 Jenkinsfile 中吗?

c - 如何从 C 中的大量单词列表中读取随机字符串?

ruby - 使用 Ruby 连接多个 IP Input 输出接口(interface),Netiom

Java编程任务效率

c++ - 运行时错误: "*** glibc detected ***: double free or corruption (out)"

Java Hibernate java.lang.IllegalArgumentException : Parameter value did not match expected type