首页 > 代码库 > 数组拆分为新数组

数组拆分为新数组

package com.classes;
//已知数组a,将奇数位置元素存到b数组中,偶数位置元素存到c数组中
public class Shuzu1118_4 {
public static void main(String[] args) {
int [] a={3,6,9,1,4,7,2,5,8};
int [] b; //定义数组b
int [] c; //定义数组c
//先找出数组b和数组从的长度
if(a.length%2==0){
b=new int[a.length/2];
c= new int[a.length/2];
}else{
b=new int[a.length/2];
c=new int[a.length/2+1];
}
int x=0;
int y=0;
for(int i=0;i<a.length;i++){
if(i%2==0){
c[x]=a[i];
x++;
}else{
b[y]=a[i];
y++;
}
}
for(int i=0;i<b.length;i++){
System.out.print(b[i]);
}
System.out.println();
for(int i=0;i<c.length;i++){
System.out.print(c[i]);
}
}
}

数组拆分为新数组