【问题标题】:Unspecified integers command-line未指定整数命令行
【发布时间】:2021-06-15 16:48:53
【问题描述】:

我正在尝试编写一个程序,将未指定数量的整数作为命令行参数传递给 main 方法并显示:

  • 用户输入的整数总数

  • 和他们的总数

这是我目前所拥有的。


public static void main(String[] args) {
        
Scanner input = new Scanner(System.in);
int count = 0;
int number, sum = 0;
do {        
number = input.nextInt();
sum = sum + number;
++count;

}
while(number != 0);
        // Displays number count.
        System.out.println("You entered "  + count + " numbers");
        // Displays the total.
        System.out.println("The sum of these numbers is " + sum);
    }
}


我想有一个方法来计算字符串中的整数个数,一个 for 循环和下一个字符以及一个整数计数来跟踪它,以及一个添加数字的方法,但我不知道该怎么写它不会出现编译错误。

【问题讨论】:

  • 哪个编译错误?您正在使用 cli 参数,但用户在程序启动后输入了输入

标签: java string command-line count


【解决方案1】:

您的程序运行良好,但不使用 cli 参数*,而是使用 用户输入

区别在于

  • 第一个参数在程序启动之前给出

    java myProgram arg1 arg2
    >> output
    
  • 在第二种情况下,在程序运行期间询问和读取参数

    java myProgram 
    >> Please give arg1:
    12
    >> Please give arg2:
    22
    >> output
    

所以当您的程序执行用户输入时,下面是 cli 参数的代码:

int count = 0;
int number, sum = 0;
for (String arg : args) {
    number = Integer.parseInt(arg);
    sum = sum + number;
    ++count;
}
System.out.println("You entered " + count + " numbers");
System.out.println("The sum of these numbers is " + sum);

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多