- Java无难事:详解Java编程核心思想与技术
- 孙鑫
- 495字
- 2025-02-26 22:40:51
1.9 交互式编程环境JShell

扫码看视频
JShell是Java 9新增的一个交互式的编程环境工具,它允许你无须编写类或者方法,就可以执行Java中的表达式。
在命令提示符窗口中执行jshell,如图1-28所示。

图1-28 JShell的交互式编程环境
你可以根据提示输入:/help intro,查看JShell的介绍,或者直接输入:/help,查看JShell的相关命令。
在提示符(jshell>)后面可以直接输入表达式,JShell会给出表达式计算的结果,如图1-29所示。

图1-29 计算表达式
图1-29中的$1和$2表示表达式计算的结果,可以用于后面的表达式计算,如图1-30所示。

图1-30 继续表达式的计算
在JShell中可以编写方法并调用它,如图1-31所示。

图1-31 编写方法并调用方法
还可以访问Java类库中的类,例如Math类,查看Math类中的方法:先输入“Math.”,然后按下Tab键(不要按回车键),就会列出该类所有的方法,如图1-32所示。

图1-32 查看Math类中的所有方法
接下来输入mi,按下Tab键,这时会自动补全min方法,如图1-33所示。

图1-33 自动补全min方法
min方法可以计算两个值的最小值,接下来输入两个数字,计算最小值,如图1-34所示。

图1-34 调用Math.min方法
在JShell的交互式编程环境中,也支持Windows命令提示符窗口的方向键操作,如↑可以列出上一个命令,↓可以列出下一个命令。
要退出JShell,只需要输入/exit即可。
JShell的更多用法就有待读者自己探索了。