2

Trying to create a 2D array that will find the sum of all elements. I am not inputting my numbers into the 2D array since I am using a driver to check my work. So far I have this - however it will not complie. What am I doing wrong?

public static double sum2d (double[ ][ ] array2d)  
{
    int sum = 0;
    for (int row=0; row < array2d.length; row++)
    {
        for (int col=0; col < array2d[row].length; col++)
        {
            sum = sum + array2d [row][col];
        }
    }

    return sum;
}
1
  • What is the compilation error? Commented Apr 7, 2016 at 0:37

4 Answers 4

7

Your method is declared to return a double but you are returning sum which is an int.

Edit: As @samrap stated in the comments, your code has formatting errors here. You are missing an opening brace {.

Sign up to request clarification or add additional context in comments.

1 Comment

Assuming he's not also missing that opening method brace, this is the answer.
1

You are missing a brace after the method signature

public static double sum2d (double[ ][ ] array2d) {  <----- put that in.

Also, you need to declare sum as double.

double sum = 0;

Note that if a method returns double, and sum has type int, you can do return sum. The problem here is that sum + array2d [row][col]; is a double so can't be assigned back to an int without a cast (but that's not what you want to do).

2 Comments

Is it not possible to write double d = 1.0; int a = d; like that without casting?
@Gendarme No, that doesn't compile. It needs to be int a = (int) d;, but that removes the fractional part.
0

Declare sum as double instead of int

Comments

0

package Homeworks;

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

int[][] a = {
        {1,1,2}, 
        {3,1,2}, 
        {3,5,3}, 
        {0,1,2}  
    };
    int sum=0;
    for (int i=0; i<a.length;i++){
      for (int j=0;j<a[i].length;j++){
        sum+=a[i][j];

      }
      System.out.println(sum);
        sum=0;
    }

} }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.