0

I'm not sure if I'm wording this correctly. I have an array policies[10], it can hold 10 floats.

I have a method that adds a float to the array when it's initialized. I have another method that totals up all the floats in the array together. The thing is that when I only have 3/10 of the array filled up, I get a null error. Can someone show me how I can fix this?

policies is a list of a class, Policy.

public float totalCoverage(){
    float total = 0;
    for (Policy x : policies){
        total += x.amount;
                }
    return total;
}

For my test, I have 3/10 arrays, if i change the array size from 10 to 3, it works.

1
  • consider using getter and setter methods instead of directly accessing members like x.amount Commented Feb 5, 2013 at 11:53

4 Answers 4

5

Well presumably you've got some elements of your array which have null values. You can just do:

for (Policy x : policies) {
    if (x != null) {
        total += x.amount;
    }
}

A better change would be to use a dynamically-sized collection like ArrayList, so that you didn't have null values to consider in the first place.

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

1 Comment

yup! that's it! so simple, i can't believe I let that slip out. Thank you very much
0

Did you try

public float totalCoverage(){
    float total = 0;
    for (Policy x : policies){
        if (x != null)
        total += x.amount;
                }
    return total;
}

Comments

0

For my test, I have 3/10 arrays, if i change the array size from 10 to 3, it works.

If i can interpret correctly, you only have 3 elements initialized in your array, remaining 7 elements are not initializaed, initializing the array doesn't mean that array elements are initialized. thus they get their default value. i..e, null thus when you call null.amount it throw NPE.

Null check :

for (Policy x : policies) {
    if (x != null) {
        total += x.amount;
    }
    else {
         System.out.println("x is null");
     }
}

Comments

0
public float totalCoverage(){

    float total = 0;
    for (int i = 0; i < array.length;i++){
       if(array[i] != null)
          total = total + array[i]
                }
       return total;
}

2 Comments

Why would you suggest using an explicit indexed for loop instead of the enhanced for loop?
@JonSkeet one possibility can be non creation of iterator objects that are used in enhanced for loops. We work in performance critical environments and found in profiling that there were huge no of iterator objects created. So we explicitly used indexed loop.

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.