The purpose of this assignment is to practice using text files, binary files, an
ID: 3604908 • Letter: T
Question
The purpose of this assignment is to practice using text files, binary files, and object serialization, for input and output, and the various methods required to do that.
Use try – catch blocks to deal with the IOException and ClassNotFoundException.
Create a file called marks.txt. Use Notepad or your Java IDE. Put at least 20 marks, not sorted, in the file (integers from 1 to 100).
Read these numbers from the file and write the following to an output file called results.txt:
the number of A’s, B’s, C’s, D’s and F’s read in (A = 80 to 100, B = 70 to 79, etc)
the highest mark, lowest mark and the average mark
DO NOT USE AN ARRAY TO STORE THE NUMBERS
You can use the following code to get started:
File inputFile = new File( "marks.txt" );
Scanner input = new Scanner( inputFile );
PrintWriter outputFile = new PrintWriter("results.txt");
while ( input.hasNext( ) )
{ your code goes here }
Explanation / Answer
Please find below the requiredc code:
//App.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
//variables to store no of each grades , sum and no of record process
int no_of_A=0,no_of_B=0,no_of_C=0,no_of_D=0,no_of_F=0,count=0,sum=0;
//initialize max and min value
int max=Integer.MIN_VALUE;
int min=Integer.MAX_VALUE;
File inputFile = new File( "marks.txt" );
try {
Scanner input = new Scanner( inputFile );
PrintWriter outputFile = new PrintWriter("results.txt");
//reading line by line
while(input.hasNext()){
count++;
//parsing string to int
int value = Integer.valueOf(input.next());sum+=value;
//calculatin min and max
if(max<value){
max=value;
}
if(min>value){
min=value;
}
//calculating no of each grades
if(value>=90)
no_of_A++;
else if(value<90 && value>=80)
no_of_B++;
else if(value<80 && value >=70)
no_of_C++;
else if(value<70 && value>=60)
no_of_D++;
else no_of_F++;
}
//Writing result to file
outputFile.write("No of A's : "+no_of_A+" ");
outputFile.write("No of B's : "+no_of_B+" ");
outputFile.write("No of C's : "+no_of_C+" ");
outputFile.write("No of D's : "+no_of_D+" ");
outputFile.write("No of F's : "+no_of_F+" ");
outputFile.write("Highets mark : "+max+" ");
outputFile.write("Lowest mark : "+min+" ");
outputFile.write("Average mark : "+(sum/count)+" ");
//closed the stream
input.close();
outputFile.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
//Input and output file
//marks.txt
89
67
89
76
88
55
67
90
67
90
56
99
54
89
57
89
88
94
26
83
//result.txt
No of A's : 4
No of B's : 7
No of C's : 1
No of D's : 3
No of F's : 5
Highets mark : 99
Lowest mark : 26
Average mark : 75
//Please do let me know if u have any concern...
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.