{1,2,3}
is not an Array initialization. You should add new int[]
, like:
int sum = sumarr(new int[] { 1,2,3 });
Question
I was running a test code to verify my friend's argument that arrays couldn't be passed in the form of an actual array instead of the name of the array variable. Here it is:
public class test
{
int sumarr( int[] arr)
{
int sum=0;
int length = arr.length;
for(int i = 0;i<length;i++)
{
sum+=arr[i];
}
return sum;
}
public static void main(String[] args)
{
int sum = sumarr({1,2,3});
System.out.println(" Sum is "+sum);
}
}
However, eclipse says that the line int sum=sumarr({1,2,3})
exhibits type mismatch and that i should change the type from int
to int[]
. How is it possible when sumarr
returns an int
value?
Pas de solution correcte
Autres conseils
{1,2,3}
is not an Array initialization. You should add new int[]
, like:
int sum = sumarr(new int[] { 1,2,3 });
There are few mistakes in your code:
you are trying to use non-static method in static one without instance so maybe consider changing your method to static one like
static int sumarr(int[] arr) {...}
you are not passing array of integers because {1,2,3}
can be used only with declaration of variable like
int[] someArray = {1,2,3};
Without this declaration part compiler can't assume correct type of array which should be created here (it could be array of long
s, float
s and any other type of numbers).
To solve that you need to provide actual type of array you want to use by
new int[]{1,2,3};
^^^^^^^^^
so change your code to
int sum = sumarr(new int[]{1,2,3});