如何在jshell 脚本中获取用户输入?或者我做错了什么?
注意:我不是在寻找如何将参数传递给 jshell 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
Run Code Online (Sandbox Code Playgroud)
如果我在 jshell 中逐行输入它可以工作,但然后我运行jshell hello.java它就不行了。投掷java.util.NoSuchElementException。
我得到的输出:
@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
Run Code Online (Sandbox Code Playgroud)
我的系统:Linux Mint 18.2(x64),JShell 版本 9.0.1
默认情况下,jshell将执行委托给远程虚拟机。如果通过,--execution local它会使用相同的 VM 进程,该进程会按预期提供 的实例System.in。根据您的问题,以下调用应该可以解决问题:
jshell --execution local hello.java
Run Code Online (Sandbox Code Playgroud)
通过以下网址查看详细信息jshell --help-extra或浏览 API 文档:https://docs.oracle.com/en/java/javase/11/docs/api/jdk.jshell/module-summary.html
| 归档时间: |
|
| 查看次数: |
2103 次 |
| 最近记录: |