jshell - unable to find printf

試著忘記壹切 提交于 2019-12-05 17:46:59

An earlier version of JShell had a printf method pre-defined but it was removed from early access builds. You can of course define your own printf method:

jshell> void printf(String format, Object... args) { System.out.printf(format, args); }

Or you can get the printing methods that were in earlier builds back by starting JShell with:

jshell --start DEFAULT --start PRINTING

(If you use only --start PRINTING you won't get the default imports.)

For more information see bug JDK-8172102 in the Java bug database and changeset b2e915d476be which implemented it.

Does it simply work without jshell? This can't work like this, since there is no such method defined outside PrintStream.

You could define your own printf like this:

jshell> private  void printf(String s) { System.out.println(s); }

And later use it :

jshell> printf("test")
test

Java is an object-oriented language and you cannot call a non-static method without an object associated with this method. printf is a non-static method of the class PrintStream and you cannot call it without a PrintStream instance.

There are some PrintStream instances in the standard Java library like System.out and System.err, so you can call System.out.printf() or System.err.printf(), but plain printf() does not work because jshell does not know which object this printf() belongs to.

This might be more convenient:

jshell> /set start -retain DEFAULT PRINTING

(Need to set this once. Next time you can simply start jshell without any argument). See official jshell documentation.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!