3

私はすでに次のコードを持っています

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ではないものとすべてがnullであるかどうかのチェックを実行しようとしています。これを行うために私はこれを試しましたが、これは私に5 p(私が望むものではない事前定義された整数配列値)を与えています。

4

3 に答える 3

4
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);

}
于 2012-08-27T03:05:15.087 に答える
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場合は、として設定されます。nullWrapper 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);

}

于 2012-08-27T02:58:40.027 に答える
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;
  }
}
于 2012-08-27T04:27:59.257 に答える