【发布时间】:2015-09-12 19:31:09
【问题描述】:
我觉得我找到了困难的部分,如果我在 main 中拥有所有内容,我可以让程序运行,但是我仍然在努力使用方法,我的指示是:写一个名为 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