英文:
Run echo example from Jshell
问题
以下是您要的翻译内容:
我读到了一个命令行参数的示例:
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
它可以从命令行正确运行,那么我该如何从 JShell 运行它?
jshell> Echo.main testing
| 创建了变量 testing,然而在声明 class main 之前无法引用它
它报告了无法引用的错误。
英文:
I read such a command line arguments example:
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
It runs properly from command line, how could I run it from Jshell?
jshell> Echo.main testing
| created variable testing, however, it cannot be referenced until class main is declared
It report error that failed to be referenced.
答案1
得分: 2
你像调用其他静态方法一样调用它:
Echo.main(new String[] { "hello", "world" });
完整会话:
$ jshell
| 欢迎使用 JShell -- 版本 11.0.8
| 要获取介绍信息,请输入:/help intro
jshell> public class Echo {
...> public static void main (String[] args) {
...> for (String s: args) {
...> System.out.println(s);
...> }
...> }
...> }
| 已创建类 Echo
jshell> Echo.main(new String[] { "hello", "world" });
hello
world
注意,你可以将 main
方法声明如下:
public static void main(String... args) { ... }
这与 String[] args
语法在二进制上是兼容的,但可以这样调用:
Echo.main("hello", "world");
英文:
You invoke it as any other static method:
Echo.main(new String[] { "hello", "world" });
Full session:
$ jshell
| Welcome to JShell -- Version 11.0.8
| For an introduction type: /help intro
jshell> public class Echo {
...> public static void main (String[] args) {
...> for (String s: args) {
...> System.out.println(s);
...> }
...> }
...> }
| created class Echo
jshell> Echo.main(new String[] { "hello", "world" });
hello
world
Note that you can declare your main
method as follows:
public static void main(String... args) { ... }
This is binary compatible with String[] args
syntax, but would allow you to invoke it as follows:
Echo.main("hello", "world");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论