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



我正试图编写一个简短的代码,从控制台读取几行代码。这是我的代码:

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不知何故并没有从控制台获得输入。当我尝试调试时,它不允许我在控制台中输入任何内容。

您的第一个eachwithReader:中遮蔽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将保留为读取器。为了进一步解决这个问题,您甚至可能想给阅读器提供自己的var名称。

相关内容

最新更新