📜  Java 9-REPL(JShell)

📅  最后修改于: 2020-11-15 03:13:42             🧑  作者: Mango


REPL代表“读取评估打印循环”。使用JShell,java具有REPL功能。使用REPL,我们可以编码和测试基于Java的逻辑,而无需使用javac进行编译,并且可以直接查看计算结果。

运行JShell

打开命令提示符,然后键入jshell。

$ jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro
jshell>

查看JShell命令

jshell命令开始运行后,键入/ help。

jshell> /help
|  Type a Java language expression, statement, or declaration.
|  Or type one of the following commands:
|  /list [|-all|-start]
|  list the source you have typed
|  /edit 
|  edit a source entry referenced by name or id
|  /drop 
|  delete a source entry referenced by name or id
|  /save [-all|-history|-start] 
|  Save snippet source to a file.
|  /open 
|  open a file as source input
|  /vars [|-all|-start]
|  list the declared variables and their values
|  /methods [|-all|-start]
|  list the declared methods and their signatures
|  /types [|-all|-start]
|  list the declared types
|  /imports 
|  list the imported items

运行JShell命令

jshell命令开始运行后,键入/ imports,然后查看使用的导入。

jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*
jshell>

在JShell中运行计算。

尝试在JShell中运行简单的计算。

jshell> 3+1
$1 ==> 4
jshell> 13%7
$2 ==> 6
jshell> $2
$2 ==> 6
jshell>

在JShell中创建和使用函数

创建一个函数doubled()以获取int并返回其doubled值。

jshell> int doubled(int i){ return i*2;}
|  created method doubled(int)
jshell> doubled(6)
$3 ==> 12
jshell>

退出JShell

输入/ exit。

jshell> /exit
| Goodbye