public static double average( double... numbers ) { 
    double total = 0.0; 
    [B][I][COLOR="Red"]for (double d : numbers)[/[/COLOR]I][/B] { 
        total += d; 
    } 
    return total / numbers.length; 
} 

can any one explain the line bold
if posseble d program too...

Recommended Answers

All 3 Replies

The part in bold is called the enhanced for loop which was introduced in Java 5. The program iterates over the variable number of double arguments (varargs) passed to the method and computes their average.

"Enhanced for loop" - new in Java 1.5, and very good.
Read it as "for each double d in numbers"
It copies each element of numbers in turn to a new double, and executes the loop once for each.
You can use this for arrays, lists, all kinds of collections, eg:

ArrayList<String> someStrings = // create and populate the arraylist of Strings
for (String s : someStrings) {
   // this is executed once for each String in someStrings.
   // the value of each String is in variable s
}

for (double d : numbers) {
total += d;
}

is equivalent to:

for (int i=0; i<numbers.length;i++){
double d = numbers[i];
total += d;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.