简体   繁体   中英

How can I sum the product of two two-dimensional arrays?

So I got a code with two arrays: one array contains tickets sold for three cinemas and the other one contains the adult and kid prices. My code outputs the total for every cinema separately (3 lines of output) but I need the total number of those 3. So instead of printing 828 for cinema1, 644 for cinema2, 1220 for cinema3 and I need it to print 2692 (total of 3 cinemas). How can I sum the 3 products with a for loop? Here's the code:

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

        float[][] a = new float[][] {{29, 149}, {59, 43}, {147, 11}};
        float[] b = new float[] {8, 4};
        String[] s = new String[] {"cinema 1", "cinema 2", "cinema 3"};
        String[] t = new String[] {"Adults", "Children"};
        int i,j;
        System.out.println("Cinema Complex Revenue\n\n");
        for ( i = 0 ; i <= 2 ; i++ )
        {
            for ( j = 0 ; j < 1 ; j++ )
            {
                System.out.println(s[i] + "\t$" + 
                 (a[i][j] * b[j] + a[i][j + 1] * b[j + 1]));
            }
        }
    }
}

And the output: 1

Just code what you want.

int i, j;
float sum = 0;
for (i = 0; i < a.length; i++) {
    for (j = 0; j < a[i].length && j < b.length; j++) {
        sum += a[i][j] * b[j];
    }
}
System.out.println(sum);

Or if you want to use only one for loop, it may be

int i;
float sum = 0;
for (i = 0; i < a.length * b.length; i++) {
    sum += a[i / b.length][i % b.length] * b[i % b.length];
}
System.out.println(sum);

All you need is 1 nested for-loop:

Integer totalCost = 0;

for( i = 0 ; i<b.length; i++ ) {
  //you should check if the a[i].length == b.length, and throw an exception if not!
  for( j = 0 ; j<a.length; j++) {
     totalCost += b[i]*a[j][i];
  }
}
System.out.println("Total cost: "+totalCost.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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