我正在尝试编写一段简短的代码,该代码将从控制台读取几行。这是我的代码:
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/