2

I saw someone creating a function that has an unknown number of arguments:

public static double calculator(double ... value){
    double result=0d;

    for(int i=0;i<?;i++){
        result+=value;
    }

    return result
}

Now I'm trying to create a for loop that will run the number of times as the number of arguments entered so:

double calc = calculator(1,2,3,4,5)

this will make the for loop run 5 times.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ishay Frenkel
  • 319
  • 1
  • 3
  • 17
  • `?` --> `value.length`. And your `+= value` won't work, you can't add a `double[]` to a `double` – fge Jan 09 '15 at 14:00
  • possible duplicate of [Java variable number or arguments for a method](http://stackoverflow.com/questions/2330942/java-variable-number-or-arguments-for-a-method) – tddmonkey Jan 09 '15 at 14:02
  • Your parameter is named wrong. Should be `values`, not `value`. – AJMansfield Jan 09 '15 at 14:02

4 Answers4

8

Internally, the value is an array, so you can treat it as such:

for(int i = 0; i < value.length; i++) {
    result += value[i];
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

The ellipsis operator (...) is just syntactic sugaring for an array. In other words, the method itself interprets the arguments as follows:

public static double calculator(double[] value)

Once you understand that, the for loop becomes obvious - you just need to iterate up to value.length:

for (int i = 0; i <value.length; i++) {
    result += value[i];
}

Or better yet, just use an enhanced for loop:

for (v : value) {
    result += v;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Wait.. Now when I'm trying to use `public static double calculator(double[] value)` it doesn't work with int's.. – Ishay Frenkel Jan 09 '15 at 14:13
  • 1
    The ellipsis operator is much more forgiving - it promotes each value separately. If you want to actually change the signature to receive a `double[]` (redundant, IMHO), you'll have to pass a `double[]` instance, even if you are filling its elements with `int`s. – Mureinik Jan 09 '15 at 14:15
1

You could use advance for loop (a.k.a for each loop) as below:

for(int element : value){
    result+=element;
}

Its same as:

for(int i = 0;i < value.length; i++){
     result+=value[i];
}
SMA
  • 36,381
  • 8
  • 49
  • 73
0

you can also use for each loop,

 for (double d : value) {

 }
atish shimpi
  • 4,873
  • 2
  • 32
  • 50