java - 计算值的总和后如何将数组传递给 main 方法?
问题描述
所以这是我目前拥有的代码。我正在尝试计算第二种方法中所有数字的总和,然后将其返回到主要方法进行显示,但我对如何正确执行此操作感到困惑。欢迎任何帮助!
public class Main {
public static void main(String[] args) {
int[] population = {
693417,
457502,
109985,
107360,
103773,
13145,
5469
};
int[] total = computeTotal(population);
for (int i = 0; i < total.length; i++);
System.out.print(total + " ");
}
public static int computeTotal(int[] population) {
int[] population2 = {
693417,
457502,
109985,
107360,
103773,
13145,
5469
};
return population2;
}
}
解决方案
如果想通过方法计算总和,你可以只返回一个整数。
public static void main(String[] args) {
int[] population = { 693417, 457502, 109985, 107360, 103773, 13145, 5469 };
int total = computeTotal(population);
System.out.print(total + " ");
}
public static int computeTotal(int[] Popu) {
int sum=0;
for(int i=0;i<Popu.length;i++)
sum+=Popu[i];
return sum;
}
顺便说一句,您编写的 for 循环将什么也不做,因为它只是运行长度时间而没有命令根据;
是每次执行循环看到的第一个命令。你应该这样写
for(int i=0;i<Popu.length;i++)
only one line code end with ;
或者
for(int i=0;i<Popu.length;i++){
...
}
运行多个代码。
推荐阅读
- amazon-web-services - AZ64压缩格式性能
- go - Golang 微服务的 Opentracing span 失败
- css - 为什么 SVG textPath 不呈现?[开发工具中的 0x0]
- google-apps-script - 如果单元格值发生更改,则调用函数
- reporting-services - 将 SSRS 报表导出到 Excel 时超出最大行数
- c# - 按特定顺序排列乌龙
- email - 更改我们的延期交货 woocommerce 电子邮件中的“延期交货”文本
- java - 是否可以让 SwaggerHub 生成没有“@schema”注释的客户端 sdk 模型(java)?
- spring - Spring 在 Kotlin 对象中自动装配是多余的吗?
- git - git - 查找创建分支的提交