user1692517
user1692517

Reputation: 1152

Java For-Loop for only items in arrays

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.

Upvotes: 0

Views: 127

Answers (4)

M.Kreusburg
M.Kreusburg

Reputation: 19

public float totalCoverage(){

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

Upvotes: 0

PermGenError
PermGenError

Reputation: 46428

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");
     }
}

Upvotes: 0

mericano1
mericano1

Reputation: 2913

Did you try

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501926

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.

Upvotes: 5

Related Questions