使用 args.length 代替 nums.length
我需要计算 arg 中的整数数量并计算平均值。目前我的代码如下,问题以粗体显示。
int count = args.length;
System.out.println(count);
int sum = 0;
for (int i = 0; i < args.length; i++)
**sum += args[i];**
**// The operator += is undefined for the argument type(s) int, String**
double average = ((double) sum) / args.length;
}
我如何才能使用 args.length 中的整数计算平均值?
I need to calculate the number of integers in an arg as well as calculate the average. Currently my code is the following with the problem in bold.
int count = args.length;
System.out.println(count);
int sum = 0;
for (int i = 0; i < args.length; i++)
**sum += args[i];**
**// The operator += is undefined for the argument type(s) int, String**
double average = ((double) sum) / args.length;
}
How do i make it so that the average is calculated using integers in args.length?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的 args 变量是一个字符串数组,您不能直接将字符串添加到 int 中。使用这个代替:
此外,使用 foreach 可以使代码更易于阅读:
your args variable is an array of Strings and you can't add directly a String to an int. Use this instead :
Moreover using a for each can make the code easier to read :
应该是
should be
命令行参数通常被接受为字符串。因此,您必须首先将其转换为数字并像这样使用它
Command-Line arguments generally accepted as Strings.So you have to first converting it to number and use it like this
问题是,当您在命令行中输入参数时,您会从 args 参数中获取字符串。您需要将它们转换为
Integer
类型。用这个,
The problem is that you get String from the
args
arguments when you enter those on the command line. You need to convert them to typeInteger
.Use this,
使用 sum += Integer.parseInt(args[i]);
Use
sum += Integer.parseInt(args[i]);