Groovy Console read input

后端 未结 5 664
闹比i
闹比i 2021-02-01 05:27

I\'m just starting to learn Groovy and I am experimenting in GroovyConsole.

Is there a way I can read user input? I have tried the code below but I get an error.

5条回答
  •  梦谈多话
    2021-02-01 05:55

    I got here trying to find out the easiest way to read user input from the command line... I found the answer elsewhere, will post here to document the 'real' Groovy way as it's still missing:

    def username = System.console().readLine 'What is your name?'
    println "Hello $username"
    

    As Larry Battle says, if using the groovy console, make sure to look at the background 'black' window for the output and to type input.

    EDIT

    In an environment where Console is not available, such as running from your IDE, probably, use this instead:

    println "What is your name?"
    println "Your name is ${System.in.newReader().readLine()}"
    

提交回复
热议问题