How to take user input in jshell script? or what I'm doing wrong?
Note: I'm NOT looking how to pass arguments to jshell script.
For example script hello.java
:
Scanner in = new Scanner(System.in);
System.out.print("Enter number n1: ");
int n1 = in.nextInt();
System.out.print("Enter number n2: ");
int n2 = in.nextInt();
System.out.println("n1 + n2 = "+ (n1 +n2));
/exit
It works if I type line by line in jshell, but then I run jshell hello.java
it doesn't. Throws java.util.NoSuchElementException
.
Output I getting:
@myMint ~/Java $ jshell hello.java
Enter number n1: | java.util.NoSuchElementException thrown:
| at Scanner.throwFor (Scanner.java:858)
| at Scanner.next (Scanner.java:1497)
| at Scanner.nextInt (Scanner.java:2161)
| at Scanner.nextInt (Scanner.java:2115)
| at (#3:1)
Enter number n2: | java.util.NoSuchElementException thrown:
| at Scanner.throwFor (Scanner.java:858)
| at Scanner.next (Scanner.java:1497)
| at Scanner.nextInt (Scanner.java:2161)
| at Scanner.nextInt (Scanner.java:2115)
| at (#5:1)
n1 + n2 = 0
My system: Linux Mint 18.2(x64), JShell Version 9.0.1
Per default, jshell
delegates execution to a remote VM. If you pass --execution local
it uses the same VM process, which provides an instance of System.in
as expected. Tailored to your question, the following call should do the trick:
jshell --execution local hello.java
See details via jshell --help-extra
or browse the API documentation at https://docs.oracle.com/en/java/javase/11/docs/api/jdk.jshell/module-summary.html