Declare two integer variables, one named i (initialized to 0) to be used as a su
ID: 3568020 • Letter: D
Question
Declare two integer variables, one named i (initialized to 0) to be used as a subscript variable and a second named priceCount.
Declare two double variables, one named grandTotal that is initialized to 0 and another named priceAvg.
Declare an array of doubles with 150 elements.
In a while loop, read the file named prices.txt that is provided and store each into your array.
After the while loop ends, i.e., there are no more prices in the file, save the value of i into priceCount.
In a for loop, spin through your array adding up the prices stored in it using the accumulator double variable named grandTotal. DO NOT spin through the empty elements at the end of your 150-element array. If you do, you will lose 50 points.
When the for loop ends, first calculate the average price in the array. Then display the number of prices in the array, skip a line and display the total (calculated and stored in variable grandTotal) with full editing, i.e., floating dollar sign with commas between the thousands places and a decimal point and two decimal places, and, last, skip a line and display the average price (calculated and stored in the variable named priceAvg) with the same full editing used for grandTotal.
Explanation / Answer
The program in java:
import java.util.*;
import java.io.*;
import java.text.*;
public class PriceTest
{
public static void main(String[] args)
{
int i,priceCount=0;
double priceAvg, grandTotal = 0;
double[] priceArray = new double[150];
try
{
BufferedReader br = new BufferedReader(new FileReader(new File("prices.txt")));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
priceArray[i] = Double.parseDouble(line);
i++;
line = br.readLine();
}
br.close();
}catch (Exception ex) { }
priceCount = i ;
for(double k = 0;k<priceCount;k++);
{
grandTotal += priceArray[k] ;
}
System.out.println("Prices in the Array: ");
priceAvg = grandTotal / priceCount;
for(int j=0; j<priceCount; j++)
{
System.out.println(priceArray[j]);
}
String pattern = "$###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
System.out.println("Grand Total :"+decimalFormat.format(grandTotal) +" ");
System.out.println("Average Price :"+decimalFormat.format(priceAvg) +" ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.