如何在 jshell 脚本中获取用户输入?

How to take user input in jshell script?

问题:

如何在 jshell 脚本 中获取用户输入?或者我做错了什么?

注意:没有

示例:

例如脚本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

您可以解决此问题,但不能直接使用基于 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()){

并且(还有)对您的代码进行小的修改(我知道这不是您要找的 - 我们在这里不使用 Scanner):

/* 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

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

$java Script.java

Launch Single-File Source-Code Programs

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

jshell --execution local hello.java

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

浏览 API 文档