Home > database >  Cannot execute .jsh file on JShell
Cannot execute .jsh file on JShell

Time:02-01

I'm a beginner at programming and practicing Java (using MacOS and jdk.17) but have been instructed to use JShell to deal with smaller/snippets of Java code. I installed JShell, opened a text editor to create and compile a file called Intro.jsh with the code:

System.out.println("Hello! Please enter some text");
String x = System.console().readLine();
System.out.println("You wrote "   x);

I then opened terminal to set my working directory to ensure the file is saved in the same environment as the directory. I opened JShell and used the following command:

jshell> --execution local Intro.jsh

I receive error messages such as:

Error:
';' expected
--execution local Intro.jsh
        ^ 
Error:
not a statement
--execution local Intro.jsh

However, when I used the command /open Intro.jsh it shows:

"Hello! Please enter some text.
 Exception java.lang.NullPointerException: Cannot invoke "java.io.Console.readLine()" because the return value of "java.lang.System.console()" is null at (#2:1)
You wrotenull"

The first line works however the second requires an input from user. Whilst I can open the file, I'm struggling to solve why I cannot execute despite double checking my wd before opening JShell.

I believe there's something I'm definitely missing out so hopefully should be a quick fix but due to limited computing experience I've tried researching for many hours but cannot seem to find out why.

Please let me know any solutions to this and any help will be greatly appreciated :)

CodePudding user response:

See the JavaDoc for System::console!

It says: "Returns the unique Console object associated with the current Java virtual machine, if any." And further down, for the return value: "The system console, if any, otherwise null."

So System::console returns null when invoked inside JShell. Seems that there is no console available for the JVM that executes JShell. And to be honest, that will not surprise me much, although I have not tried it before.

JShell itself is running on that console, having a second console would not make much sense in this context.

CodePudding user response:

The command line for jshell that is equivalent to using /open Intro.jsh from within jshell is:

jshell --startup Intro.jsh
  • Related