打印在for循环中填充的数组

时间:2017-05-02 18:04:05

标签: java arrays for-loop

我今天要来一个非常基本的任务,不知何故让我很困惑。 我有一个看起来像这样的数组:

Array

以下是代码:

 double population[][] = {{281.0, 296.0, 325.0, 371.0, 384.5},
    {298.6, 241.2, 301.2, 342.8, 388.7},
    {362.9, 284.1, 276.8, 353.6, 395.1},
    {393.4, 344.8, 295.6, 298.3, 375.0}};
    int year[] = {2011, 2016, 2021, 2026, 2031};
    String ageGroup[] = {"15-19", "20-24", "25-29", "30-34",};
    String output = "Actual and Projected Population in thousands by Age Group (CSO 2016)";
    output += String.format("\n%10s", "");

    for (int i = 0; i < year.length; i++) {
        output += String.format("%10s", year[i]);
    }

    output += String.format("%10s", "%Change");
    double change[] = new double[ageGroup.length];
    for (int i = 0; i < population.length; i++) {
        output += String.format("\n%10s ", ageGroup[i]);
        for (int j = 0; j < population[i].length; j++) {
            output += String.format("%10.1f", population[i][j]);
        }
        change[i] = (((population[i][4] - population[i][0])/
                population[i][0]) * 100);
        output += String.format("%10.1f", change[i]);

    }     
    output += String.format("\n\nTotal (15 - 34): ");           
    System.out.println(output);

}

您可以清楚地看到我错过了最低价值 - 1335.9, 1166.1, 1198.6, 1543.3。通过添加全年获得这些值,例如2011年 - 281 + 298.6 + 362.9 + 393.4

我无法弄清楚如何制作一个for循环,以便按照我想要的方式打印出来。

我试过了:

            double total[] = new double[ageGroup.length];
            double hold = 0;
            for(int i = 0; i < population.length; i++){
                    total[i] += hold;       
            for(int j = 0; j < population[i].length; j++){  
                    hold += population[j][i];      

我也试过在这里添加

 for (int i = 0; i < population.length; i++) {
            output += String.format("\n%10s ", ageGroup[i]);
            for (int j = 0; j < population[i].length; j++) {
                output += String.format("%10.1f", population[i][j]);
            }
            change[i] = (((population[i][4] - population[i][0])/
                    population[i][0]) * 100);
            output += String.format("%10.1f", change[i]);
            total[i] = (population[0][i] + population[1][i]+ population[2][i]+population[3][i]+population[4][i]);

        }   

现在我对这么简单的任务如何让我如此困难感到困惑。

3 个答案:

答案 0 :(得分:2)

教师不会教授OO思维,这是一种犯罪行为,迫使学生混淆阵列,而不是对域进行建模。 叹息

我认为这里有两把钥匙。首先,将计算与表示分开。其次,要意识到行是年龄组,列是年。真的应该有这些东西的方法,而不是只有一个main方法。此外,标题和一些绒毛可以在最终输出中修复。

此外,此代码使用数组的[4]代替硬编码,例如.length,以便更轻松地处理添加另一年或其他年龄组。

//
// a 2d array, where row is for a given agent group, and column
//  is for a given year
//
static double population[][] = { { 281.0, 296.0, 325.0, 371.0, 384.5 },
        { 298.6, 241.2, 301.2, 342.8, 388.7 },
        { 362.9, 284.1, 276.8, 353.6, 395.1 },
        { 393.4, 344.8, 295.6, 298.3, 375.0 } };
static int year[] = { 2011, 2016, 2021, 2026, 2031 };
static String ageGroup[] = { "15-19", "20-24", "25-29", "30-34", };


public static void main(String[] args)
{
    //
    // hold the totals
    //
    double[] yearTot = new double[year.length]; // total by year
    double[] agTot = new double[ageGroup.length]; //total by ag
    double[] chngAG = new double[ageGroup.length]; //change

    // loop over every age group
    for (int ag = 0; ag < ageGroup.length; ++ag) {
        // get the population for the age group, which is
        // one row in the data
        double[] valsForAG = population[ag];


        // loop over every year, which a column in a given age group
        for (int yr = 0; yr < year.length; ++yr) {
            // get the specific value
            double valForAgInYear = valsForAG[yr];

            // add to the total for the year and to the age group value
            yearTot[yr] += valForAgInYear;
            agTot[ag] += valForAgInYear;

        } // for every year 

        int en = ageGroup.length;
        int st = 0;

        // after processing an age group, calculate the change
        chngAG[ag] = ( ( (valsForAG[en] - valsForAG[st]) /
                valsForAG[st]) * 100);
    } // for every age group

    //
    // do the output
    //

    // header row
    System.out.printf("%10s", "");
    for (int y = 0; y < year.length; ++y) {
        System.out.printf("\t%7d", year[y]);
    }
    System.out.printf("\t%10s%n", "%Change");

    // data
    for (int ag = 0; ag < ageGroup.length; ++ag) {
        System.out.printf("%10s", ageGroup[ag]);
        for (int yr = 0; yr < year.length; ++yr) {
            System.out.printf("\t%7.1f", population[ag][yr]);
        }
        System.out.printf("%10.1f", chngAG[ag]);
        System.out.println();
    }

    //output the totals
    System.out.println();

    System.out.printf("%10s", "Totals:");
    for (int t = 0; t < yearTot.length; ++t) {
        System.out.printf("\t%7.1f", yearTot[t]);
    }
    System.out.println();
}

输出

         2011   2016     2021    2026    2031    %Change
15-19   281.0   296.0   325.0   371.0   384.5      36.8
20-24   298.6   241.2   301.2   342.8   388.7      30.2
25-29   362.9   284.1   276.8   353.6   395.1       8.9
30-34   393.4   344.8   295.6   298.3   375.0      -4.7
     

总计:1335.9 1166.1 1198.6 1365.7 1543.3

答案 1 :(得分:0)

public static void main(String[] args) {
    double population[][] = {{281.0, 296.0, 325.0, 371.0, 384.5}, {298.6, 241.2, 301.2, 342.8, 388.7}, {362.9, 284.1, 276.8, 353.6, 395.1}, {393.4, 344.8, 295.6, 298.3, 375.0}};

    //1. Step: Find the longest of the arrays
    //You need this if the length of the arrays is different, for example:
    /*
    double population[][] = {
     {281.0, 296.0, 325.0, 371.0, 384.5},
     {298.6, 241.2, 301.2, 342.8, 388.7, 0},
     {362.9, 284.1, 276.8, 353.6, 395.1, 1, 2},
     {393.4, 344.8, 295.6, 298.3, 375.0, 0.5}
    };
    */
    int lengthOfLongestArray = population[0].length;
    for(int i = 0; i < population.length; i++){
        if(population[i].length > lengthOfLongestArray){
            lengthOfLongestArray = population[i].length;
        }
    }

    //2. Step: calculate the sum
    double result[] = new double[lengthOfLongestArray];
    for(int i = 0; i < population.length; i++){
        for(int j = 0; j < population[i].length; j++){
            result[j] += population[i][j];
        }
    }

    System.out.println(Arrays.toString(result));
}

说明: 为了避免混淆循环和奇特的逻辑,我创建了一个数组,它将保存名为 result 的计算结果。

  1. 步骤: 通过将此结果数组的长度设置为填充2D数组(也称为矩阵)中行的最长长度,我们可以处理行长度不完全相同的情况(请参阅示例I注释掉。

  2. 步骤: 然后我们循环遍历2D数组并对值求和。当我们在2D数组中经历一行时,我们可以从“j&#39; j”中获取值。我们正在检查的行的位置,并将其添加到我们在&#39; j&#39;中的值。在结果数组中的位置。

  3. 干杯, 甲

答案 2 :(得分:-2)

double population[][] = { { 281.0, 296.0, 325.0, 371.0, 384.5 }, { 298.6, 241.2, 301.2, 342.8, 388.7 },
            { 362.9, 284.1, 276.8, 353.6, 395.1 }, { 393.4, 344.8, 295.6, 298.3, 375.0 } };
    int year[] = { 2011, 2016, 2021, 2026, 2031 };
    String ageGroup[] = { "15-19", "20-24", "25-29", "30-34", };
    String output = "Actual and Projected Population in thousands by Age Group (CSO 2016)";
    output += String.format("\n%10s", "");

    for (int i = 0; i < year.length; i++) {
        output += String.format("%10s", year[i]);
    }

    output += String.format("%10s", "%Change");
    double change[] = new double[ageGroup.length];
    for (int i = 0; i < population.length; i++) {
        output += String.format("\n%10s ", ageGroup[i]);
        for (int j = 0; j < population[i].length; j++) {
            output += String.format("%10.1f", population[i][j]);
        }
        change[i] = (((population[i][4] - population[i][0]) / population[i][0]) * 100);
        output += String.format("%10.1f", change[i]);

    }
    output += String.format("\n\nTotal (15 - 34): ");

    // here i changed the code
    // this loop will print the last from (15 to 35)
    // the outer loop iterate like 2011 2016 and so one
    for (int i = 0; i < 5; i++) {
        double temp = 0;
        // the inner loop iterate from up to down and add values
        for (int j = 0; j < 4; j++) {
            temp = temp + population[j][i];
        }
        output += String.format("%10.1f", temp);
    }
    System.out.println(output);