java 数组去0 生成新数组 代码。

给出一个数组 int score [] = {1,2,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};要求以上数组中值为0的去掉,将不为0的值存入一个新的数组 newScore[] 中。并打印出来。(小菜刚接触 一些类库都还没接触 学完数组那节出得习题 各位高手尽量使用for循环 条件语句 和方法 得一项或几项完成)

第1个回答  推荐于2016-03-18
public class Du21 {

public static void main(String[] args) {

int score[] = {1,2,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};

int[] tempAry = new int[score.length];

int nonZeroCount = 0;

for(int i = 0, j= 0;i < score.length; i++){
if(score[i] != 0){
tempAry[j++] = score[i];
nonZeroCount++;
}
}

int newScore[] = new int[nonZeroCount];

for(int i = 0; i < newScore.length; i++){
newScore[i] = tempAry[i];
System.out.print(newScore[i] + ", ");
}
}

}

-----------testing
1, 2, 3, 4, 5, 6, 6, 5, 4, 7, 6, 7, 5,本回答被提问者采纳
相似回答