【问题标题】:Java - Passing arguments to the Main method [duplicate]Java - 将参数传递给Main方法[重复]
【发布时间】:2016-06-22 18:42:12
【问题描述】:

我只是一个用 Java 编写程序的初学者。如何将参数(Array of strings) 传递给主方法?我正在使用 Eclipse 作为 IDE

public static void main(String[] args) {
    // TODO Auto-generated method stub
    if (args[0].equals("-h"))
        System.out.print("Hello,");
    else if (args[0].equals("-g"))
        System.out.print("Goodbye,");

    // print the other command-line arguments
    for (int i = 1; i < args.length; i++)
        System.out.print(" " + args[i]);

    System.out.println("!");
}

【问题讨论】:

  • 除非您确定 args 数组中至少有一个元素,否则不应访问 args[0]。
  • 我也是个初学者,只是好奇为什么要检查 args 是否等于“-h”?

标签: java eclipse command-line-arguments


【解决方案1】:

运行 > 运行配置 > Java 应用程序 > 参数 > 程序 论据


另外,请确保您的代码在没有传递参数时可以正常工作,不要直接从数组中选取值

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        if (args != null && args.length > 0) {
            if (args[0].equals("-h"))
                System.out.print("Hello,");
            else if (args[0].equals("-g"))
                System.out.print("Goodbye,");

            // print the other command-line arguments
            for (int i = 1; i < args.length; i++)
                System.out.print(" " + args[i]);

        } else{
            System.out.print("No Arguments passed");
        }
        System.out.println("!");
    }

【讨论】:

    【解决方案2】:

    您可以在运行配置 -> Java 应用程序 -> 参数 -> 程序参数中传递参数

    链接:- http://www.cs.colostate.edu/helpdocs/eclipseCommLineArgs.html

    【讨论】:

    【解决方案3】:

    右击|运行为 |打开运行对话框|(x)=参数

    然后给你 args

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 2021-08-30
      • 2012-03-03
      • 2013-10-04
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      相关资源
      最近更新 更多