问题描述
如何在 jshell脚本中接受用户输入?还是我做错了什么?
How to take user input in jshell script? or what I'm doing wrong?
注意:我不正在寻找.
例如脚本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
.
It works if I type line by line in jshell, but then I run jshell hello.java
it doesn't. Throws 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的代码解决.
You can solve this issue, but not directly with JShell based code.
有一个项目jshell_script_executor
: https://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)
and (also) small modification of your code (I know this is not exactly what you are looking for - we don't use Scanner here):
/* 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
嗯...实际上,它也可以与您的代码一起使用-稍作修改:
Well ... in fact it will work with your code as well - slightly modified:
/* 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
这篇关于如何在jshell脚本中接受用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!