operator * cannot be applied to double,double[]

Hi all!

I am trying to write a java code to multiply numbers using the variable length arguments list. But, I am getting an error. Below is my code:

[code]
import java.util.Scanner;
public class Product
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
double a = 0.0, b = 0.0, c = 0.0, d = 0.0;
System.out.print ("Please enter four numbers, a, b, c, d: ");
a = input.nextDouble();
b = input.nextDouble();
c = input.nextDouble();
d = input.nextDouble();
System.out.printf("The product of a and b is: %f ", prod(a,b));


}

public static double prod (double... numbers)
{
double product = 1.0;
for (double d : numbers)
{
product *= numbers;
}
return product;
}
}
[/code]

This is the error i get when i try to execute:
operator * cannot be applied to double,double[]
product *= numbers;

Would appreciate any help!
Thanks.

Comments

  • [code] public static double prod (double... numbers)
    {
    double product = 1.0;
    for (double d : numbers)
    {
    product *= numbers;
    }
    return product;
    }

    [/code]

    Here your are trying to find product of double and double array. Which is meaningless.

    So make a small difference in the code.

    Solution 1:
    Instead of calling prod(a,b) you can write a*b

    Solution 2:
    Rewrite prod(a,b) like as follows

    [code]
    double prod(double a, double b)
    {
    return a*b;
    }
    [/code]

    Solution 3: (Worst solution)

    [code]
    public static double prod (double... numbers)
    {
    double product = 1.0;
    for (double d : numbers)
    {
    product *= numbers[d];
    }
    return product;
    }

    Don't forget to Thank Me
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion