日期:2014-05-20 浏览次数:20723 次
public class xiti{ public static void main(String args[]){ int oldArr[] = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; //newArr = new int[oldArr.length]; int newArr[] = null; int x = 0; //newArr数组键位的基数 for(int i = 0 ; i < oldArr.length ; i ++ ){ if(oldArr[i] == 0){ //不知该如何删除数组中的索引 oldArr[i] = null; }else{ x++; System.out.println("现在的x是"+x); //程序第一次循环能执行到这里 newArr[x] = oldArr[i]; //到这里必定报main错,原因应该是newArr[x] 这个用法有误 } } System.out.println("oldArr去除0后变成了:"); for(int i:oldArr){ System.out.print(i+"+"); } System.out.println("新数组newArr的样子为:"); for(int i:newArr){ System.out.print(i+"+"); } } }
public class Xiti { public static void main(String args[]){ int oldArr[] = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; //newArr = new int[oldArr.length]; int newArr[] = null; int x = 0; //newArr数组键位的基数 //计算非零元素的数目 for(int i:oldArr){ if(i!=0) x++; } newArr=new int[x]; for(int i = 0 ,j=0; i < oldArr.length ; i ++ ){ if(oldArr[i] != 0){ newArr[j] = oldArr[i]; j++; } } System.out.println("oldArr:"); for(int i:oldArr){ System.out.print(i+","); } System.out.println("新数组newArr的样子为:"); for(int i:newArr){ System.out.print(i+","); } } }