Write a program that will read a file of 6 student records called marks.txt, whi
ID: 3556473 • Letter: W
Question
Write a program that will read a file of 6 student records called marks.txt, which you must create yourself as shown below. Each student record consists of a student number (7 digits), a subject (for example "math") and an integer mark.
An example of two records would look like this:
2134523
Math
47
75676881
English
98
Your task is to read the file and create two files, one called pass.txt and the other fail.txt. Both output files should contain only subject and mark.
3000 points avaiable for program that will run on cmd.exe
Explanation / Answer
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
class gradeFiles
{
public static void main (String args[])
{
String strLine;
String subject = null;
int mark = 0;
int line;
BufferedReader br = null;
try
{
line = 1;
br = new BufferedReader(new FileReader("marks.txt"));
File file1 = new File("pass.txt");
File file2 = new File("fail.txt");
if (!file1.exists())
{
file1.createNewFile();
}
if (!file2.exists())
{
file2.createNewFile();
}
FileWriter fw1 = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw1 = new BufferedWriter(fw1);
FileWriter fw2 = new FileWriter(file2.getAbsoluteFile());
BufferedWriter bw2 = new BufferedWriter(fw2);
while ((strLine = br.readLine()) != null)
{
if (line % 2 == 0)
subject = strLine;
else if (line % 3 == 0)
{
mark = Integer.parseInt(strLine);
if (mark > 60)
bw1.write(subject + " " + mark);
else
bw2.write(subject + " " + mark);
line = 0;
}
line ++;
}
bw1.close();
bw2.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)
br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.