从数组求和数字(java)

时间:2016-09-15 16:57:53

标签: java

我很难弄清楚如何总结这个二维阵列中的所有移民(或阵列中的任何数字),我不能想到一个有效的方法除了总结之外所有大量垃圾的价值 提前谢谢

这里是我的代码:

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++){

    }
}

}

3 个答案:

答案 0 :(得分:2)

我建议创建可以称为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方法,以打印有关特定国家/地区的信息。

答案 1 :(得分:0)

可能是以下代码帮助您

long totalImmigrants=0;
double worldTotal=0.0;
double totalPopulation=0.0;


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]);
    totalImmigrants+=data[row][1];
    worldTotal+=data[row][2];
    totalPopulation+=data[row][3];
}

在代码末尾你应该打印三个变量。

答案 2 :(得分:-1)

    int totalIm =0 ;
    for(int row= 0 ;row<  data.length;row++){
       totalIm += data[row][1];
    }//  System.out.println(totalIm)