Get 3rd, 4th , 3rd, 4th element from an array


Get elements from an given array based on some index sequence. like in this get 3rd element then 4th, then 3rd then 4th on so on...

public class TeampClass {

public static void main(String[] args) {

char[] A = {'1','2','3','7','4','d','a','w','q','4','2','d','a','w','q','4','2'};
char[] b = new char[A.length];

boolean flag  = false;
int count = 0;
for(int i=0;i<A.length;i++){

if(i==0){
flag = true;
if(i+2 <=A.length){
b[count] = A[i+2];
i +=1;
}
}
else{
if(flag == false){
if(i+2 <A.length){
b[count] = A[i+3];
i +=2;
flag = true;
}
}else{

if(i+4 <A.length){
b[count] = A[i+4];
i +=3;
flag = false;
}
}
}
count++;
}

System.out.println(Arrays.toString(A));
System.out.println(Arrays.toString(b));

}


}


output

[1, 2, 3, 7, 4, d, a, w, q, 4, 2, d, a, w, q, 4, 2]
[3, a, 4, w, 2, ]

Post a Comment

Previous Post Next Post