简体   繁体   English

打印数组已填充到for循环中

[英]Printing array that was filled in a for loop

I am coming today with a very basic task that somehow confused me really hard. 今天我要完成一项非常基本的任务,这使我感到非常困惑。 I have an array that looks like that : 我有一个看起来像这样的数组:

排列

Here is the code: 这是代码:

 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);

}

As you can clearly see I am missing the bottom values - 1335.9, 1166.1, 1198.6, 1543.3 . 如您所见,我错过了最低值1335.9, 1166.1, 1198.6, 1543.3 These values are gained by adding full year eg 2011 - 281 + 298.6 + 362.9 + 393.4 这些值是通过将全年相加得出的,例如281 + 298.6 + 362.9 + 393.4

I cannot figure out how to make a for loop in order for this to print out the way I want to. 我无法弄清楚如何制作一个for循环,以便以此打印出我想要的方式。

I tried : 我试过了 :

            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];      

I also tried adding it here 我也尝试过在这里添加

 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]);

        }   

Now I am just left confused on how such an easy task made me stuck so hard. 现在,让我感到困惑的是,如此简单的任务使我如此艰难。

It is a crime that instructors do not teach OO thinking out of the gate, forcing students to muddle through arrays rather than modeling the domain. 教员不开门见山地讲授面向对象的思维是一种犯罪,它迫使学生混淆数组而不是对领域建模。 sigh . 感叹

There are two keys here, I think. 我认为这里有两个键。 First, separate the calculation from presentation. 首先,将计算与表示分开。 Second, realize that rows are age groups and columns are years. 其次,认识到行是年龄组,列是年。 Really there should be methods for this stuff rather than just in a single main method. 确实,应该有针对这些东西的方法,而不仅仅是一个main方法。 Also, the title and some fluff can be fixed in the final output. 同样,标题和一些绒毛可以固定在最终输出中。

Also, rather than hard coding, eg, [4] , this code uses the .length of the array to make it somewhat easier to deal with adding another year or another age group. 另外,此代码不是使用硬编码(例如[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();
}

Output 产量

  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 

Totals: 1335.9 1166.1 1198.6 1365.7 1543.3 总计:1335.9 1166.1 1198.6 1365.7 1543.3

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));
}

Explanation: To avoid confusing loops and fancy logic I created an array which will hold the result of the calculation called result . 说明:为了避免混淆循环和奇特的逻辑,我创建了一个数组,该数组将保存名为result的计算结果

  1. Step: By setting the length of this result array to the length longest of the rows in the population 2D array (aka. matrix) we handle the situation when the rows are not exactly the same length (see the example I commented out). 步骤:通过将此结果数组的长度设置为总体2D数组(也称为矩阵)中行的最长长度,我们可以处理行的长度不完全相同的情况(请参见我注释掉的示例)。

  2. Step: Then we just loop through the 2D array and sum the values. 步骤:然后,我们循环遍历2D数组并求和。 As we go through of a row in your 2D array we can take the value from the 'j' position of the row we are checking and add it to the value we have in the 'j' position in the result array. 当我们遍历2D数组中的一行时,我们可以从要检查的行的'j'位置获取值,并将其添加到结果数组中'j'位置的值。

Cheers, A. 干杯,A。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM