【问题标题】:I want to give out only one Argument instead of all 4我只想给出一个参数而不是全部 4
【发布时间】:2023-03-11 02:00:01
【问题描述】:

我希望用户可以输入四个参数,这会导致用户输入的数字相加。但是现在我遇到了问题,如果用户想给出更少的论点。我该如何总结呢?

public class Sum {

    public static void main(String[] args) {
        int  q = Integer.parseInt(args[0]);
        int  w = Integer.parseInt(args[1]);
        int  e = Integer.parseInt(args[2]);
        int  r = Integer.parseInt(args[3]);

        int summe = q + w + e + r; 
        System.out.println(summe);

【问题讨论】:

  • 使用 Scanner 代替命令行参数,并在循环中调用它们。询问用户是否要输入(更多)数据
  • 使用 for 循环遍历 args
  • System.out.println(Stream.of(args).mapToInt(Integer::parseInt).sum());

标签: java arguments


【解决方案1】:

您必须检查输入参数的数量(即args.length),以免尝试访问args 数组的无效索引。

如果您只想计算总和,则不需要所有这些变量:

public static void main(String[] args) {
    int sum = 0;
    for (int i = 0; i < args.length; i++) {
         sum += Integer.parseInt (args[i]);
    }
    System.out.println(sum);
}

【讨论】:

  • 为什么使用索引循环而不是增强的 for 循环?
  • @khelwood 没有特殊原因。两者都可以。
  • 我对@khelwood 的回答是:使与问题代码的关联更清晰。 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 2020-08-24
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多