Modify the Total program so that it shows the average, not the total of the inputs. import java.io.File; import java.io.

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

Modify the Total program so that it shows the average, not the total of the inputs. import java.io.File; import java.io.

Post by answerhappygod »

Modify the Total program so that it shows the average,
not the total of the inputs.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
/**
This program reads a file with numbers, and writes the
numbers to another
file, lined up in a column and followed by their
average.
*/
public class Total
{
public static void main(String[] args) throws
FileNotFoundException
{
// Prompt for the input and output file
names
Scanner console = new
Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter
objects for reading and writing
File inputFile = new
File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new
PrintWriter(outputFileName);
// Read the input and write the output

int tc = 0;
double total = 0;
while (in.hasNextDouble())
{
double value =
in.nextDouble();
out.printf("%17.2f\n",
value);
total = total + value;
tc++;
}

double average = total / tc;
out.printf("Average:%10.2f\n",average);

in.close();
out.close();
}
}
1: Compare outputkeyboard_arrow_up
Output is nearly correct; but whitespace differs. See highlights
below. Special character legend
Input
numbers.txt output.txt
Your file content
32.00 54.00 67.50 29.00 35.00 80.00 115.00 44.50 100.00 65.00
Average: 62.20
Expected file content
32.00 54.00 67.50 29.00 35.00 80.00 115.00 44.50 100.00 65.00
Average: 62.20
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply