运行 JShell 中的 echo 示例

huangapple go评论63阅读模式
英文:

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");

huangapple
  • 本文由 发表于 2020年9月8日 15:58:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63789556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定