How to return a specific element of an array?
Solution 1
You code should look like this:
public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
Main points here are method return type, it should match with array elements type and if you are working from main()
- this method must be static also.
Solution 2
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
Solution 3
Make sure return type of you method is same what you want to return. Eg: `
public int get(int[] r)
{
return r[0];
}
`
Note : return type is int, not int[], so it is able to return int.
In general, prototype can be
public Type get(Type[] array, int index)
{
return array[index];
}
Nik
Updated on October 16, 2020Comments
-
Nik over 3 years
I want to return odd numbers of an array yet Eclipse doesn't seem to accept my return
array[i];
code. I think it requires returning a whole array since I set an array as a parameter to my method. As I said before, I need to pass an array and get a specific element of that array in return. Even if I make that array static, how do I return a single element?Edit : Alright then, here it is:
public class newClass{ public static void main(String[] args) { int [] newArray= new int [4]; int [] array = {4,5,6,7}; newArray[0] = array[0]+array[1]+array[2]+array[3]; newArray[1] = array[0]*array[1]*array[2]*array[3]; newArray[2] = findOut(array); } public static int findOut (int [] array3) { int e1=0; int e2=0; for (int i=0; i<array3.length; i++) { if (array3[i]%2==0) { e1+=array3[i]; array3[i]=e1 return array3[i]; } else { e2+=array3[i]; array3[i]=e2; return array3[i]; } } } }
I know there are probably more than a few mistakes here but I'm working on it and I'm not only returning odd numbers, I also add them together.