0

In my program, i "deleted" an element by turning it into a null as you can't delete an element from an array so employee [i] = null. However, I was wondering, if I wanted to work with the array that had a null element, like add all the numbers in the array, how do I do this without any problems?

[UPDATE:]

My array contains the first names, last names and ages of 4 employees, I've "deleted" one of the employees details by making it null. As per all of the suggestions I got, I tried to add all the ages using:

int sum = 0;

for (int i = 0; i < employee.length; i++) {
    if (employee[i] != null)
        sum += employee[i].getAge();
}

but all I get is that sum = 1.

4 Answers 4

1

If the only operation you're going to perform on your array is the sum of all elements, it would make more sense to set the deleted elements to 0 instead of null. This way, you will not need the extra null check on every iteration.

Sign up to request clarification or add additional context in comments.

5 Comments

my array does not contain only number, it contains the first names, last names and ages of 4 employees. I want to add the ages of 3 employees after I've deleted one of the employees information.
Ok, in that case you will need the null check like other answers have pointed out. Also, a cleaner way to do this is to put your Employee objects in a List, so you can use the .remove() method to delete elements in the list.
I tried that. But that just keep giving me that the sum of employee[i].getAge is 1.
Have you tried printing out all the (non-null) elements of the array? What does this show you?
That works fine. All the elements are printed out (except for the null one).
0

You have to check if that element is null or not. If it is, add to the sum. If not, do nothing.

int sum = 0;

for (int i = 0; i < employee.length; i++) {
    if (employee[i] != null)
        sum += employee[i];
}

1 Comment

I did int sum = 0; for (int i = 0; i < employee.length; i++) { if (employee[i] != null) sum += employee[i].getAge; } and the sum keeps coming up to 1 all the time.
0

public int addAllNums(int[] nums) { int sum=0; for(int i=0;i<nums.length;i++) { if(nums[i]!=null)sum+=nums[i]; } }

2 Comments

@demongolem, thanks for the edit. Didn't see that. :)
Two of the other answers are exactly what I posted. How to remove duplicate answers?
0

You just have to iterate over your array and check if the current employee is not null :

int sum = 0;
for(int i = 0; i < employee.length; i++) {
    if(employee[i] != null) {
        sum += employe[i].getNumber();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.