5

问题:

如何在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

如果我在 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

我的系统:Linux Mint 18.2(x64),JShell 版本 9.0.1

4

3 回答 3

4

默认情况下,jshell将执行委托给远程 VM。如果你通过它,它使用相同的 VM 进程,它提供了一个预期--execution local的实例。System.in根据您的问题量身定制,以下调用应该可以解决问题:

jshell --execution local hello.java

通过https://docs.oracle.com/en/java/javase/11/docs/api/jdk.jshell/module-summary.html查看详细信息jshell --help-extra或浏览 API 文档

于 2019-12-25T07:27:42.783 回答
3

您可以解决此问题,但不能直接使用基于 JShell 的代码。

有这个项目jshell_script_executorhttps ://github.com/kotari4u/jshell_script_executor

您可以下载它,并在里面稍作修改JShellScriptExecutor.java

try(JShell jshell = JShell.create()){

// This call will map System.in in your main code
// to System.in inside JShell evaluated code
try(JShell jshell =
  JShell.builder()
    .in(System.in)
    .out(System.out)
    .err(System.err)
    .build()){

和(也)你的代码的小修改(我知道这不是你正在寻找的 - 我们在这里不使用扫描仪):

/* Put this code into file.jshell */
import java.io.*;

InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int n1;
System.out.print("Enter the number: ");
n1 = Integer.parseInt(in.readLine());

int n2;
System.out.print("Enter the number: ");
n2 = Integer.parseInt(in.readLine());

System.out.println("n1 + n2 = " + (n1 + n2));

你可以让它运行:

> javac src/main/java/com/sai/jshell/extension/JShellScriptExecutor.java
> java -cp src/main/java com.sai.jshell.extension.JShellScriptExecutor ./file.jshell
Enter the number: 1
Enter the number: 2
n1 + n2 = 3

好吧...实际上它也可以与您的代码一起使用-稍作修改:

/* Put this code into file_scanner.java */
import java.util.Scanner;

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));

试一试

> java -cp src/main/java com.sai.jshell.extension.JShellScriptExecutor ./file_scanner.java
Enter number n1: 1
Enter number n2: 2
n1 + n2 = 3
于 2018-02-13T15:02:41.170 回答
3

从JDK11可以直接执行java源文件:

$java Script.java

请参阅启动单文件源代码程序

于 2018-08-23T11:16:37.637 回答