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;
}
}
Eran
395k57 gold badges725 silver badges792 bronze badges
-
look at the type of the result you are trying to return, and the type you said you would return (in the method declaration) - are they the same?panini– panini2014年10月19日 19:52:34 +00:00Commented Oct 19, 2014 at 19:52
1 Answer 1
Change public int[] sum(int s[])
to public int sum(int s[])
Since your method should return a single int, not an array.
answered Oct 19, 2014 at 19:50
lang-java