Declare two integer variables, one named i (initialized to 0) to be used as a su
ID: 3568021 • 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
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
?
public class Average {
public static void main(String[] args) {
int i=0;
int priceCount;
double grandTotal=0.0,priceAvg;
double[] price=new double[150];
DecimalFormat defaultFormat = new DecimalFormat("#.##");
BufferedReader br = null;
try {
String sCurrentLine;
String fileName="prices.txt";
br = new BufferedReader(new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
price[i++]=Double.parseDouble(sCurrentLine);
}
priceCount=i;
for (int j = 0; j < priceCount; j++)
{
grandTotal+=price[j];
}
priceAvg=grandTotal/priceCount;
System.out.println("No of prices :"+priceCount);
System.out.println("");
System.out.println("Total : $"+defaultFormat.format(grandTotal));
System.out.println("");
System.out.println("Average : $"+defaultFormat.format(priceAvg));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.