0
public class Labwork
{
   public static void main(String[] args)
   {
      int [][] x = { {1, 2, 3}, {4, 5, 6, 7, 8}, {11, 12} };
      int [][] y = { {20, 12}, {10, 11}, {12, 13, 14, 15} };
      int [][][] z = { x, y };
      System.out.println("" + sum(x) + " Expected: 59");
      System.out.println("" + sum(y) + " Expected: 107");
      System.out.println("" + sum(z) + " Expected: 166");
   }
   //sums up 2d array
   public static int sum (int [][] a)
   {
      int sum = 0;
      for(int b = 0; b < a.length; b++)
      {
         for(int c = 0; c < a[b].length; c++)
         {
            sum += a[b][c];
         }
      }
      return sum;
   }
   //sums up 3d array
   public static int sum (int [][][] a)
   {
      int sum = 0;
      for(int d = 0; d < a.length; d++)
      {
         for(int e = 0; e < a[d].length; e++)
         {
            for(int f = 0; f < a[d][e].length; f++)
            {
               sum += a[d][e][f];
            }
         }
      }
      return sum;
    }
}

So the first part of my assignment was to finish the sum method so that the output is the expected sum. Now I have to change the the sum methods so that they complete their tasks using one loop. I don't even know where to start with this and any help would be appreciated.

Philip
  • 9
  • 2

1 Answers1

1
import java.util.stream.IntStream;

Use this int sumA=IntStream.of(AA).sum(); AA is our int array.

You have multidimensional arrays so you have to map all in a stream. So you use this try it.

  IntStream intStream = Arrays.stream(a).flatMapToInt(x -> Arrays.stream(x));
  int sum = intStream.sum();