Why does my jshell instance (JDK Version 9-ea) unable to identify printf()
statement ? Below is the error I observe,
jshell> printf("Print number one - %d",1)
| Error:
| cannot find symbol
| symbol: method printf(java.lang.String,int)
| printf("Print number one - %d",1)
| ^----^
I am able to access printf, provided I specify it in a regular way.
jshell> System.out.printf("Print number one - %d",1)
Print number one - 1$1 ==> java.io.PrintStream@1efbd816
Any pointers?
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.
来源:https://stackoverflow.com/questions/43798036/jshell-unable-to-find-printf