Groovy Console read input

我们两清 提交于 2019-12-02 18:15:17

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()}"
def readln = javax.swing.JOptionPane.&showInputDialog
def username = readln 'What is your name?'
println "Hello $username."

Your code works.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
print "Input:"
def userInput = br.readLine()
println "You entered: $userInput"

Assuming you're on windows, the only problem is that the input is being read from the console in the background that is launched before groovyconsole.

You could try something like this, which works at the command-line of any o/s, but also in the GoovyConsole - where it pops up a dialog [as noted in a previous post]:

def cons = System.console()
def yn
if (cons) {
    yn = {((cons.readLine(it + " (y/n) ")?:"n").trim()?:"n")?.charAt(0).toLowerCase().toString() }
} else {
    cons = javax.swing.JOptionPane.&showInputDialog
    yn = {((cons(it + " (y/n) ")?:"n").trim()?:"n")?.charAt(0).toLowerCase().toString() }
}
if (yn("Did you want to do something?") == 'y')
    ...do something here!...

if your System.console() is null, you can

Scanner scan = new Scanner(System.in);
String s = scan.nextLine()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!