Home > database >  How to sum elements of multiple arrays from a method (in Java)?
How to sum elements of multiple arrays from a method (in Java)?

Time:10-23

I have a set of 1d arrays that are being pulled from a method (tableMethod) - i want to grab those 1d arrays, then sum all the elements in each 1d array. How can I do that?

I have two loops

  • one that can sum a 1d array by itself
  • another that can display all the 1d arrays

I'm having difficulty combining the for loops so that it can grab each 1d array, sum it, then move on to the next 1d array, sum it, and so forth

the result should look something like:

  • total: 391

  • total: 393

  • total: 3903

  • total: 39104

  • total: 39031 ... and so forth

      int sum = 0;
      int w = 0;
      int[] arrayOne = tableMethod(table, w);
    
      for (int k = 0; k < arrayOne.length; k  ) {
          sum = sum   arrayOne[k];
      }
      for (int i = 0; i < arrayOne.length; i  ) {
          System.out.println(Arrays.toString(tableMethod(table, i)));
      }
      System.out.println(sum);
    

    }

CodePudding user response:

Something like this would work,

import java.util.stream.IntStream;

int n = <max value of w>
int sum = 0;

for (int i = 0; i < n; i  ) {
   int[] array = tableMethod(table, i);
   int arr_sum = IntStream.of(array).sum();
   System.out.println(arr_sum); //single array sum

   sum  = arr_sum;
}
System.out.println(sum); //total sum

CodePudding user response:

The code should be simply using nested loops (inner loop to calculate a sum may be replaced with stream):

int n = ... ; // a number of 1d arrays
int total = 0;
for (int i = 0; i < n; i  ) {
    int[] arr = tableMethod(table, i);
    int sum = Arrays.stream(arr).sum();
    System.out.println(sum);
    total  = sum;
}
System.out.println(total);
  • Related