尝试在Groovy中获取输入时出错

时间:2018-12-02 00:53:27

标签: groovy readline

我对groovy还是很陌生,我在Groovy控制台和Eclipse中使用下面的代码(将其作为Groovy脚本运行),但是却出现以下错误。

可以帮忙吗?

println("What is your name ");
def fName = System.console().readLine()
println("Hello" + fName)

Groovy控制台中的错误

groovy> print("What is your name ") 
groovy> def fName = System.console().readLine() 
groovy> println("Hello" + fName) 

你叫什么名字
抛出异常

java.lang.NullPointerException:无法在空对象上调用方法readLine()

at ConsoleScript54.run(ConsoleScript54:2)

Eclipse中的错误

你叫什么名字 捕获:java.lang.NullPointerException:无法在空对象上调用方法readLine() java.lang.NullPointerException:无法在空对象上调用方法readLine()     在sample.run(sample.groovy:2)

1 个答案:

答案 0 :(得分:1)

System.console()在终端中运行时有效,但在Eclipse等IDE中不起作用。获得单行输入的更好方法是System.in.newReader().readLine()