本帖最后由 momoxixi 于 2015-11-2 11:16 编辑
- /**
- * Created by mo on 15/11/2.
- *
- * 定义一个新数组,遍历原数组,如果元素不为0则加入新数组
- * 新数组长度不确定 所以决定先遍历一遍 查出来原数组有几个0 再创新新数组
- */
- class ccc {
- public static void main(String[] args) {
- int arr[] = {1,0,4,3,0,5,6,7,2,0,8,3,0,4,2,5,0,42,3,5,6,0,31,4,54,6,0,4};
- printArr(del0(arr)); //调用方法
- }
- public static int[] del0(int[] arr){
- int count=0; //原数组中0的个数
- for (int nums:arr){
- if (nums == 0){
- count++;
- }
- }
- int[] arr1 = new int[arr.length-count]; //新数组长度=原数组.length-count
- for (int i=0,y=0;i<arr.length;i++){ //y为新数组的index,遍历到0的时候跳过循环,y不自增
- if (arr[i] == 0){
- continue;
- }else {
- arr1[y] = arr[i];
- y++;
- }
- }
- return arr1;
- }
- public static void printArr(int[] arr){
- for (int nums:arr){
- System.out.print(nums+" ");
- }
- }
- }
复制代码 |