2012-08-27 31 views
3

我已經有下面的代碼的java得到陣列的數量值

public class Qn3 
{ 
    static BigDecimal[] accbal= new BigDecimal[20]; 
    private static Integer[] accnums = new Integer[5]; 

    public static void main(String[] args) 
    { 
     int count; 
     accnums = {1,2} //i cant add this line of code as well, what is wrong? 
     while(accnums.length < 5) 
     { 
       count = accnums.number_of_filled_up_indexes 
       //this is not actual code i know 
      //do this as the number of values in the array are less than 5 
      break; 
      } 
      //do this as number of values in the array are more than 5 
    } 
} 

我必須用這個代碼就沒有改變,這是一個需求量的,所以請不要建議使用ArrayList和這樣的(我知道其他陣列類型和方法)

問題是,因爲我已經宣佈accnums必須包含只有5個值,這是預定義的。

我試圖執行一個檢查,不是空的,如果都是null。要做到這一點,我試過這個,但這是給我5 p(預定義的整數數組值不是我想要的)。

+0

對不起,誤解了這個問題。看到MadProgrammer的答案 - 只需使用一個for循環並將您的計數保存在一個變量中,您可以爲每個非空的索引增加一個變量。最後的計數將是非空值的總數。 – msrxthr

回答

3
public static void main(String[] args) 
{ 
    int count = 0; 
    accnums = new Integer[] {1,2,null,null,null}; 
    for (int index = 0; index < accnums.length; index++) 
    { 
     if(accnums[index] != null) 
     { 
      count++; 
     } 
    } 

    System.out.println("You have used " + count + " slots); 

} 
+0

'accnums.length - Collections.frequency(Arrays.asList(accnums),null)' – oldrinb

+1

PS'accnums'應該是'new Integer [5] {1,2,null,null,null}' – oldrinb

+0

@veer首先,不允許'List's:P,其次 - 歡呼 – MadProgrammer

2

嘗試......

accnums[0] = new Integer(1); 
accnums[1] = new Integer(2); 

如果雙方在宣言和初始化的時間和數組做下面將工作。

Integer[] arr = new Integer[]{1,2,3}; 
Integer[] arr = {1,2,3} 

但是,當你只需要聲明數組作爲

Integer[] arr = new Integer[3]; // Still array holds no Object Reference Variable 

後來這種方法進行初始化...

arr = new Integer{1,2,3,}; // At this time it hold the ORV 

陣總是被初始化爲類或方法是否使用範圍,因此對於int數組,所有值將被設置爲默認值0,對於Integer,它將是null,作爲其Wrapper object

如:

Integer[] arr = new Integer[5]; 

    arr[0] = 1; 
    arr[1] = 2; 

    System.out.println(arr.length); 

    for (Integer i : arr){ 

     if (i!=null){ 

      count++; 

     } 



    } 

    System.out.println("Total Index with Non Null Count :"+count); 

}

+0

是tks,將值添加到整數數組。但仍然是我的主要問題是檢查Integer數組中有多少個被填充。 tks – JackyBoi

+0

好吧,看看我編輯的答案.....如何檢查有多少被填滿 –

0
accnums[0] = 1; 
accnums[1] = 2; 
final int count = accnums.length 
    - Collections.frequency(Arrays.asList(accnums), null); 
System.out.println("You have used " + count + " slots"); 

,或者,如果你真的必須做手工......

int count; 
for (final Integer val : accnums) { 
    if (val != null) { 
    ++count; 
    } 
}