nasa
nasa

Reputation: 11

Using sum method to get the sum of an array

I am trying to get the sum of an array using sum method, but it shows up saying "incompatible types" for "return result" part at the very end. I tried to find out how I can fix it, but I'm kind of stuck.

public class Prog2
{

    public Prog2()
    {
        int a[] = {7, 8, 9, 9, 8, 7};

        System.out.println(sum(a));

    }

    public int[] sum(int s[])
    {
        int result = 0;

        for (int i = 0; i < s.length; i ++)
        {
            result += s [i];
        }
        return result; 
    }
}

Upvotes: 0

Views: 116

Answers (1)

Eran
Eran

Reputation: 394106

Change public int[] sum(int s[])

to public int sum(int s[])

Since your method should return a single int, not an array.

Upvotes: 4

Related Questions