【问题标题】:How to display command line args from main method如何从主要方法显示命令行参数
【发布时间】:2015-09-12 19:31:09
【问题描述】:

我觉得我找到了困难的部分,如果我在 ma​​in 中拥有所有内容,我可以让程序运行,但是我仍然在努力使用方法,我的指示是:写一个名为 sumInts 的方法,它可以采用可变数量的 int 参数并返回这些参数的总和。要汇总的整数必须作为命令行参数输入。命令行参数可以在 Eclipse 中模拟。在 main 方法中,显示在命令行中输入的整数。然后执行 sumInts 并显示它返回的总和。

我这辈子都不知道应该如何调用我的方法让它打印出我的命令行的总和下面是我的代码。

public class CommandLineSum {

    public static void main(String[] args) {

        System.out.println("# of command line args: " + args.length);

        System.out.print("Command line args in order: ");

        for (int i = 0; i < args.length; i++) {
            System.out.print(args[i] + " ");

        }

        System.out.println("\nThe sum is: ");

    }

    public static int sumInts(String[] args) {
        int sum = 0;

        for (int i = 0; i < args.length; i++) {
            sum += Integer.parseInt(args[i]);
        }
        return sum;

    }
}

我的输出是:

# of command line args: 9
Command line args in order: 1 2 3 4 5 6 7 8 9
The sum is:

我需要它是:

# of command line args: 9
Command line args in order: 1 2 3 4 5 6 7 8 9
The sum is: 45

【问题讨论】:

  • System.out.println("\nThe sum is: " + sumInts(args));
  • 哇。让我用我的书拍拍自己。

标签: java methods command-line parameter-passing


【解决方案1】:

您必须从 main() 调用您的方法 sumInts()。传递args 作为参数。

你会得到想要的结果:

System.out.println("\n总和为:" + sumInts(args));

【讨论】:

    【解决方案2】:
    class A
    {
        public static void main(String args[])
        { 
          A obj = new A(); // creating object
          obj.sumInts(args); // calling function
        }
    
        public static void sumInts(String[] arr) {
            int sum = 0;
            String outputString="";
            for (int i = 0; i < arr.length; i++) {
    
                outputString  = outputString+arr[i];
    
                if(i !=arr.length-1){
                    outputString = outputString+", ";
                }
                sum += Integer.parseInt(arr[i]);
            }
    
            System.out.println("Passing ["+outputString+"]");
            System.out.println("Sum  is "+sum);
        } 
    }
    

    /*

    另存为A.java 编译:javac A.java 运行:java A 10 20 3040 */

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 2018-11-02
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2019-12-12
      • 2015-04-15
      相关资源
      最近更新 更多