【问题标题】:pass array through method (java command line arguments)通过方法传递数组(java命令行参数)
【发布时间】:2015-04-22 08:42:58
【问题描述】:

我想知道如何在方法中检查 args.length。

例如:

public static void commandLineCheck (int first, int second){
    if (args.length==0){
        //do something with first and second
    }
}

public static void main(String[] args) {
    int first = Integer.parseInt(args[0]);
    int second = Integer.parseInt(args[1]);
    commandLineCheck(first, second);
}

执行此操作时出现“找不到符号:args”错误。现在,我想我也需要通过该方法传递 args[] 。我已经尝试过了,但它给了我一个“”错误。有适合初学者的解决方案吗?

编辑:非常感谢你们的快速响应!成功了!

【问题讨论】:

    标签: java command-line-arguments


    【解决方案1】:

    像这样更改您的代码(您需要将数组的参数传递给您的检查方法)

    public static void commandLineCheck (int first, int second, String[] args){
        if (args.length==0){
            //do something with first and second
        }
    }
    
    public static void main(String[] args) {
        int first = Integer.parseInt(args[0]);
        int second = Integer.parseInt(args[1]);
        commandLineCheck(first, second, args);
    }
    

    它会起作用的。但是,下面的测试(args.length==0) 没有多大意义,因为您已经通过在 main 方法中从中提取两个值来假设 args.length 大于或等于 2。因此,当您使用 commandLineCheck 方法时,此测试将始终为 false。

    【讨论】:

      【解决方案2】:

      您需要将String [] args 传递给您的commandLineCheck 方法。这与为 main 方法声明数组的方式相同。

      public static void commandLineCheck (String[] args){
          if (args.length==0){
              //do something with first and second
          }
      }
      

      您可能还想稍微更改一下您的 main 方法和 commandLineCheck 方法。

      public static void commandLineCheck(String [] args) {
          /* make sure there are arguments, check that length >= 2*/
          if (args.length >= 2){
              //do something with first and second
              int first = Integer.parseInt(args[0]);
              int second = Integer.parseInt(args[1]);
          }
      }
      
      public static void main(String[] args) {
          commandLineCheck(args);
      }
      

      【讨论】:

        猜你喜欢
        • 2010-12-11
        • 2014-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-15
        • 1970-01-01
        • 2021-11-29
        • 2021-12-13
        相关资源
        最近更新 更多