0

I am trying to write a brief code that would read a few lines from console. This is my code:

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
    }
}

This is input from the console:

1
20

And this is the error I get:

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

I have a feeling that somehow Groovy does not get inputs from console. When I tried debugging it did not allow me to enter anything into console.

1 Answer 1

1

Your first each shadows the it from the withReader:

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)

Give the inner it a name (like you do later with d) and the original it will remain the reader. To further untangle this you might even want to give the reader its own var name.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I see - it overrides "it". Correct?
yes, without naming it for yourself, groovy uses it and shadows the outer it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.