需求:
目前存在數組:int[] arr = {0,8,0,12,1,0,3,6,0} ,編寫一個函數接收該數組,然後把該數組的0清空,然後返回一個不存在0元素的數組。
步驟:
計算新數組的長度。 原來的數組長度-0的個數import java.util.*;
class MyClass
{
public static void main(String[] args)
{
int[] arr = {0,0,12,1,0,4,6,0};
arr = clearZero(arr);
System.out.println("數組的元素:"+Arrays.toString(arr));
}
public static int[] clearZero(int[] arr){
//統計0的個數
int count = 0; //定義一個變量記錄0的個數
for(int i = 0 ; i<arr.length ; i++){
if(arr[i]==0){
count++;
}
}
//創建一個新的數組
int[] newArr = new int[arr.length-count];
int index =0 ; //新數組使用的索引值
//把非的數據存儲到新數組中。
for(int i = 0; i<arr.length ; i++){
if(arr[i]!=0){
newArr[index] = arr[i];
index++;
}
}
return newArr;
}
}