I need to mix two arrays into one whose lengths we insert and fill with randoms. The question is that I have to mix them in the following way: three first of the first array, three first of the second array, three of the first array, three of the second array ... etc, and my code does not work well, sometimes it exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12 at arrays.Ej_6.main (Ej_6.java:46)
How can I solve it?
package arrays;
import java.util.Scanner;
public class Ej_6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner (System.in);
System.out.println("Introduce la dimension del primer array");
int n=input.nextInt();
System.out.println("Introduce la dimension del segundo array");
int d=input.nextInt();
int[] p_array = new int[n];
int[] s_array = new int[d];
for (int i=0;i<p_array.length;i++){
p_array[i]=(int)(Math.random()*10);
System.out.print(p_array[i] + " ");
}
System.out.println();
for (int j=0;j<s_array.length;j++){
s_array[j]=(int)(Math.random()*10);
System.out.print(s_array[j] + " ");
}
System.out.println();
int[] mezcla = new int [n+d];
int in_parray=0;
int in_sarray=0;
int x=0;
for (x=0;x<mezcla.length;x++){
if((x+2)%2==0 && in_parray<p_array.length){
for (int k=0;k<3;k++){
mezcla[x]=p_array[in_parray];
in_parray++;
x++;
}
}
System.out.println();
if ((x+3)!=0 && in_sarray<s_array.length){
for (int k=0;k<3;k++){
mezcla[x]=s_array[in_sarray];
x++;
in_sarray++;
}
}
}
for (int z=0;z<mezcla.length;z++){
System.out.print(mezcla[z] + " ");
}
}
}