Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java return array in method

I'm doing my first steps in java, so my question is simple - I have an array with 8 integers and I want to return an array that contains the odd index elements from the original array. what's wrong with the method deceleration? Any other implementation tips would be appreciated.

P.S - I know that I don't have to use method here, it's just for the exercise.

package com.tau;

public class Main {


    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};


        System.out.println("1.e odd index numbers in array : " + oddIndex(arr));

        int j = 0;
        public static int[] oddIndex(int[] array){
            int newArrSize = array.length;
            if ((newArrSize % 2) != 0) {
                newArrSize--;
            }

            int[] newArr = new int[newArrSize];

            for (int i = 0; i < array.length; i++)
                if ((array[i] % 2) == 0) {
                    newArr[j] = array[i];
                    j++;
                }
            return newArr;

      }
    }


} 
like image 748
Niminim Avatar asked Sep 11 '15 07:09

Niminim


1 Answers

1)You cannot have methods inside method in Java. Move your oddIndex() methods outside main() method.

2) And you cannot local variables of a method in another method. So I moved your variable j to oddIndex() method

public class Main {

    public static void main(String[] args) {

        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };

        System.out.println("1.e odd index numbers in array : " + oddIndex(arr));

    }

    public static int[] oddIndex(int[] array) {
        int j = 0;
        int newArrSize = array.length;
        if ((newArrSize % 2) != 0) {
            newArrSize--;
        }

        int[] newArr = new int[newArrSize];

        for (int i = 0; i < array.length; i++)
            if ((array[i] % 2) == 0) {
                newArr[j] = array[i];
                j++;
            }
        return newArr;

    }

}

And also, as Jhamon commented, your method name and logic inside are not matched. Odd index != odd value.

like image 71
Suresh Atta Avatar answered Nov 14 '22 23:11

Suresh Atta