I already have the following code
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
}
}
I must use this code there is no changing this is a requirment, so please dont suggest to use arraylist and such (i am aware of other array types and methods)
The problem is that as I have already declared that accnums
must contain only 5 values, that is predefined.
I am trying to perform a check whether the ones that are not null and if all are null. To do this I have tried this but this is giving me 5 p(pre-defined integer array value not what I want).
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);
}
Try this...
accnums[0] = new Integer(1);
accnums[1] = new Integer(2);
Both the below will work if done during Declaration and Initializing time of and array.
Integer[] arr = new Integer[]{1,2,3};
Integer[] arr = {1,2,3}
But when you just declare the array as
Integer[] arr = new Integer[3]; // Still array holds no Object Reference Variable
then later initialize it this way...
arr = new Integer{1,2,3,}; // At this time it hold the ORV
Array are always initialized whether used at class or method scope , so for an int array all the values will be set to default as 0, and for Integer
it will be null
, as its an Wrapper object
.
Eg:
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);
}
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");
or, if you really must do it manually...
int count;
for (final Integer val : accnums) {
if (val != null) {
++count;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.