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;
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With