Write a very small Java program that consist of: 1. A single class named Asn1BAp
ID: 3541118 • Letter: W
Question
Write a very small Java program that consist of:
1. A single class named Asn1BApp. Save the definition of this class in a file named Asn1BApp.java
2. The single class Asn1BApp should contain only the main method, and should read a file of numbers (of type double) from a file named asn1b.in. Should write the sum of those numbers (with appropriate label) and average of those numbers (with appropriate label). The sum and average should be displayed using 2 decimal points.
3. All output should be written to a file named asn1b.out. Use Scanner class for input and PrintWriter class for output.
asn1b.in file:
34.5984
3.402
9874.544333
22.1
0.0003
23.4343
8324.12
3002.32
1231.1100021
5.2
8.012
9942.21
678932.23221
12.1
908.87
234.509233
A single class named Asn1BApp. Save the definition of this class in a file named Asn1BApp.java The single class Asn1BApp should contain only the main method, and should read a file of numbers (of type double) from a file named asn1b.in. Should write the sum of those numbers (with appropriate label) and average of those numbers (with appropriate label). The sum and average should be displayed using 2 decimal points. All output should be written to a file named asn1b.out. Use Scanner class for input and PrintWriter class for output.Explanation / Answer
// make sure asn1b.in exists in same directory as this program
import java.util.Scanner;
import java.io.*;
public class Asn1BApp
{
public static void main(String args[]) throws IOException
{
//read
Scanner rw = new Scanner(new FileInputStream("asn1b.in"));
//write
PrintWriter fw = new PrintWriter("asn1b.out");
double sum=0,num=0,avg;
int n=0;
while(rw.hasNext())
{
num=rw.nextDouble();
sum =sum+num;
n++;
}
avg = sum/n;
rw.close();
fw.printf("Sum: %.2f",sum);
fw.println();
fw.printf("Average: %.2f",avg);
fw.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.