已知,数组int oldArr[]={1,2,3,4,5,0,0,6,7,4}
将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为int newArr[]={1,2,3,4,5,6,7,4}
应该如何编写代码,自己只能将0的元素去掉后打印输出成1,2,3,4,5,6,7,4 应该怎能打印成int newArr[]={1,2,3,4,5,6,7,4} 求详细解释
2 回答
已采纳
损失函数
TA贡献114条经验 获得超93个赞
public static void arrayDemo()
{
int oldArr[]={1,2,3,4,5,0,0,6,7,4};
List<Integer> convertList = new ArrayList<Integer>();
for (int old : oldArr) {
if(old != 0)
{
convertList.add(old);
}
}
Object[] newArr = convertList.toArray();
for (Object object : newArr) {
System.out.println(object);
}
}
如果不明白,我再来加上注释。
望采纳!
慕莱坞9220042
TA贡献377条经验 获得超508个赞
你好:
我自己写了一个,可能代码比较笨拙,你可以看下:
public static void main(String[] args) { int oldArr[] = {1,2,3,4,5,0,0,6,7,4}; int j = 0; //要定义新数组的长度计算 int newArrLenght = 0; for (int i = 0; i < oldArr.length; i++) { if(oldArr[i] != 0){ newArrLenght++; } } //初始化新数组,循环取出非零数字添加到新数字里 int newArr[] = new int[newArrLenght] ; for (int i = 0; i < oldArr.length; i++) { if(oldArr[i] != 0){ newArr[j] = oldArr[i]; j++; } } for (int i = 0; i < newArr.length; i++) { if(i == 0){ System.out.print("int newArr[]={" + newArr[i] + ","); }else if(i == newArr.length-1){ System.out.print(newArr[i] + "}"); }else{ System.out.print(newArr[i] + ","); } } }
望采纳!
添加回答
举报
0/150
提交
取消