Groovy Console read input

后端 未结 5 654
闹比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:48

    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!...
    

提交回复
热议问题