Xander Yamyam
Xander Yamyam

Reputation: 21

Array Element Position Java

Are there any other ways to print the position of your element inside the array? Even[position in the array]=even numbers Odd[position in the array]=odd numbers

public class samt {
    public static void main(String[] args){
        int Num[] = {1,2,3,4,5,6,7,8,9,10};
        int ctr=1, ctr2=0;
        for(int i=0;i<10;i++) {
            if(Num[i]%2==0) {       
                System.out.print("Even"+"["+ctr+"]=");
                System.out.println(Num[i]);
                ctr+=2;
            }
        }
        for(int i=0;i<10;i++) {
            if(Num[i]%2!=0) {
                System.out.print("Odd"+"["+ctr2+"]=");
                System.out.println(Num[i]);
                ctr2+=2;
            }   
        }   
    }   
}

Upvotes: 1

Views: 62

Answers (1)

Japhei
Japhei

Reputation: 635

If your only goal is to shorten your code you can use lists and filter for even and odd numbers:

Integer[] num = {1,2,3,4,5,6,7,8,9,10};
List<Integer> list = Arrays.asList(num);
List<Integer> even = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
List<Integer> odd = list.stream().filter(n -> n % 2 == 1).collect(Collectors.toList());
even.forEach(n -> System.out.println("Even" + "["+ list.indexOf(n) + "]=" + n));
odd.forEach(n -> System.out.println("Odd" + "["+ list.indexOf(n) + "]=" + n));

With this the output lookes the same as with your code:

Even[1]=2
Even[3]=4
Even[5]=6
Even[7]=8
Even[9]=10
Odd[0]=1
Odd[2]=3
Odd[4]=5
Odd[6]=7
Odd[8]=9

Note that the runtime of this is probably longer than with your attempt.

Upvotes: 1

Related Questions