1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Adding array elements

Discussion in 'Java' started by noirnuit, Jan 25, 2010.

  1. noirnuit

    noirnuit New Member

    Joined:
    Jan 25, 2010
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    For some reason, the last line doesn't work at all. :confused: I've looked through different forums and kept finding the same code for adding the integers in an array, but nothing happens.

    Code:
        public static void main(String[] args)
        {
            int[][] array2D = {{0,1,2,3},{4,5,6,7},{8,9,10,11},{12,13,14,15}};
            
            for (int row=0; row<array2D.length; row++)
            {
                for (int col=0; col<array2D[row].length+1; col++)
                {    
                    if (col<array2D[row].length)
                    {
                        System.out.print(array2D[row][col] + "\t");
                    }
                    else
                        System.out.println();
                }
            }
            int sum = 0;
            for (int i=0; i<array2D.length; i++){
    [B]            sum += array2D[i]; //this one has the error[/B]
            }
            System.out.println ("The sum of all the elements is: " + sum);
    
    I've just started learning Java this month, so I really need the help. Thanks!
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
    array2D is a 2D array and you are adding it like 1D.
     
  3. noirnuit

    noirnuit New Member

    Joined:
    Jan 25, 2010
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    I finally figured out that the format of the sum should be similar to the one above it. Thanks for the tip!:happy:
     

Share This Page