# Average of arrays issue

• 04-08-2013, 10:08 PM
dbbl21
Average of arrays issue
Hi this is my first post so I hope I'm doing this correctly.
An array of prices is to be entered by the user and then the average of the prices is supposed to be returned. I'am trying to figure out how to get this program to read the length of the array of prices that is given and not what I am initially setting "length" to. Any help would be appreciated.

/*Complete the method named averagePrice, in the program below, named Prices.java, so that it accepts an array of prices
as a parameter, and returns the average price. You may assume all prices are double values.
Complete the following code:*/

import java.util.Scanner;

public class Wiley044Prices
{//Start of class
/**
A method to determine and return the average price
*/
public static double averagePrice(double[] priceData)
{//Start of averagePrice

double total = 0;

for (double element : priceData)

{
total = total + element;
}
double average = 0;

average = total / priceData.length;

return average;

}//End of averagePrice

public static void main (String[] args)
{//Start of main

int length = 0;
double[] priceData = new double[length];
int currentSize = 0;
System.out.println("Please enter prices, Q to quit: ");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble() && currentSize < priceData.length)
{
priceData[currentSize] = in.nextDouble();
currentSize++;
}

System.out.println(currentSize);
System.out.println("The average price is " + averagePrice(priceData));
}//End of main
}//End of class
• 04-09-2013, 04:31 AM
Junky
Re: Average of arrays issue
If the array has a size of 20 and user only enters 6 values then you will need to keep track of how many by using a counter and incrementing each time a new value is entered.

BTW you have created an array with a size of zero. Not very useful.