class NewArray {
public static void main (String[] args) {
int [] a = {1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5};
// 定义一个新数组
int [] b = new int[7];
// 定义一个变量j,作为数组b的下标
int j = 0;
for (int i = 0; i < a.length; i++) {
// 判断不为0的元素
if (a[i] != 0) {
// 若不为0,存入新的数组b
b[j] = a[i];
// b的下标加1
j++;
}
}
// 循环打印新的数组b
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
}
练习
import java.util.Arrays;
public class MainTest {
public static void main(String[] args) {
int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int newArr[]=Arrays.stream(oldArr).filter(e->e!=0).toArray();
System.out.print(Arrays.toString(newArr));
}
}
[1, 3, 4, 5, 6, 6, 5, 4, 7, 6, 7, 5]
public class Demo17 {
public static void main(String[] args) {
int j=0;
int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int newArr[]=new int [oldArr.length];
for(int i=0;i
newArr[j]=oldArr[i];//元素为0的不存入newArr
j++;
}
}
for(int m:newArr){
if(m==0){
break;
}
System.out.print(m+" ");}
}
}