gpt4 book ai didi

java - 对数组中的数字求和(java)

转载 作者:行者123 更新时间:2023-12-01 09:30:00 27 4
gpt4 key购买 nike

我很难弄清楚如何对这个二维数组中的所有移民(或数组中的任何数字)求和,除了求和之外,我想不出一种有效的方法所有大量的值都是垃圾提前致谢

这是我的代码:

public class App {
public static void main(String[] args) {

Object[][] data = { { "United States", 45785090, 19.8, 14.3 }, { "Russia", 11048064, 4.8, 7.7 },
{ "Germany", 9845244, 4.3, 11.9 }, { "Germany", 9845244, 4.3, 11.9 },
{ "Saudi Arabia", 9060433, 3.9, 31.4 }, { "United Arab Emirates", 7826981, 3.4, 83.7 },
{ "United Kingdom", 7824131, 3.4, 12.4 }, { "France", 7439086, 3.2, 11.6 },
{ "Canada", 7284069, 3.1, 20.7 }, { "Australia", 6468640, 2.8, 27.7 },
{ "Spain", 6466605, 2.8, 13.8 } };

System.out.printf("%22s %12s %17s %14s\n", "contry", "immigrants ", "% world total ", "% population");

for (int row = 0; row < data.length; row++) {
System.out.printf("%22s %12s %17s %14s\n", data[row][0], data[row][1], data[row][2], data[row][3]);
}
int totalIm ;
for(int row= 0 ;row< data.length;row++){

}
}

}

最佳答案

我建议创建一个单独的类,可以称为 CountryImmigrants 。这样的类将有四个字段:

private String countryName;
private int immigrantsCount;
private double immigrantsPercentPop;
private double immigrantsPercentGlob;

然后你就会有List<CountryImmigrants> list = ... ,然后你就可以写:

int sum = list.stream().mapToInt(country -> country.getImmigrantsCount()).sum();

然后您可以覆盖 toString() CountryImmigrants中的方法用于打印有关特定国家/地区的信息。

关于java - 对数组中的数字求和(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39516556/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com