How to return a specific element of an array?

前端 未结 4 1816
臣服心动
臣服心动 2020-12-20 01:49

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 a

相关标签:
4条回答
  • 2020-12-20 02:20

    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];
    }
    
    0 讨论(0)
  • 2020-12-20 02:26

    (Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:

    array3[i]=e1
    

    Also the findOut method doesn't return any value if the array length is 0. Adding a return 0; at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.

    0 讨论(0)
  • 2020-12-20 02:38

    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.

    0 讨论(0)
  • 2020-12-20 02:44

    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;
    }
    
    0 讨论(0)
提交回复
热议问题