java题求代码,4、现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: int newArr[]={1,3,4,5,6,6,5,4,7,6,7,5}
程序员文章站
2022-03-03 10:56:35
public class TEST { 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= new int[oldArr.length] ; ......
public class test {
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= new int[oldarr.length] ;
int n=0;
for (int i=0;i<oldarr.length;i++) {
if(oldarr[i]==0) {}
else {
newarr[n]=oldarr[i];
n++;
}
}
for(int i=0;i<newarr.length;i++)
{
if(newarr[i]!=0) {system.out.print(newarr[i]);}
}
}
}
注意int [] newarr={};会报错,因为没有固定的长度
exception in thread "main" java.lang.arrayindexoutofboundsexception: 0
at test.main(test.java:11)
推荐阅读