Question :create a n application containing an array that stores 20 proces such as RM2.34, RM7.89 and so on. The application should display the sum of all the prices , display all values less than 5.00 , calculate average price and display all values higher than calculated average.
Requirement : I need your help for modification which can input prices by user input.
For mine program i make the prices static.
Code :
public class PricesArray {
// declare the prices array
private static double[] prices = new double[20];
public static void main(String[] args) {
// fill the array with sample prices
prices[0] = 5.5;
prices[1] = 7.36;
prices[2] = 9.22;
prices[3] = 2.47;
prices[4] = 12.54;
prices[5] = 14.99;
prices[6] = 12.2;
prices[7] = 54.78;
prices[8] = 62.14;
prices[9] = 14.99;
prices[10] = 2.50;
prices[11] = 33.78;
prices[12] = 98.98;
prices[13] = 22.47;
prices[14] = 78.32;
prices[15] = 3.05;
prices[16] = 11.35;
prices[17] = 25.73;
prices[18] = 8.88;
prices[19] = 54.92;
// display the sample values:
System.out.print("Prices:\n");
for (int i = 0; i < 20; i++) {
System.out.println("$" + prices[ i ]);
}
// display the sum of all prices
System.out.printf("\nSum: $%.2f\n\n", sum());
// display all values less than $5.00
System.out.printf("Values less than $5.00:\n%s\n", valuesLessThan5());
// display the average of the prices
System.out.printf("Average of the prices: $%.2f\n\n", average());
// display all values that are higher than the calculated average value
System.out.printf("Values higher than the average:\n%s\n",
valuesHigherThanAverage());
}
// returns the sum of all prices
private static double sum() {
double total = 0;
for (int i = 0; i < 20; i++) {
total += prices[ i ];
}
return total;
}
// returns all values less than $5.00
private static String valuesLessThan5() {
String values = "";
for (int i = 0; i < 20; i++) {
if (prices[ i ] < 5.00) {
values += "$" + prices[ i ] + "\n";
}
}
return values;
}
// returns the average of the prices
private static double average() {
return sum() / 20.00;
}
// returns all values that are higher than the calculated average value
private static String valuesHigherThanAverage() {
double avg = average();
String values = "";
for (int i = 0; i < 20; i++) {
if (prices[ i ] > avg) {
values += "$" + prices[ i ] + "\n";
}
}
return values;
}
}