This program calculates the GPA of all students in the text
This program calculates the GPA of all students in the text file. It must be named \"project.java\". It accepts input from a file, called \"grade_in.txt\", which holds five students\' grade. It then calculates the GPA of all students in \"grade_in.txt\" and writes appropriate output to another file, called \"GPA_out.txt\". Note: A 4.0 A-:3.7 B+:3.3 B:3 B-:2.7 C+:2.3 C:2 C-:1.7 D+:1.3 D:1 D-:0.7
\"grade_in.txt\"
Sample \"GPA_out.text\"
Solution
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class Grades {
public static void main(String[] args) {
BufferedReader br = null;
int maxStudents = 10;
int index=0,count=0;
double sum[] = {0,0,0,0,0,0,0,0,0,0};
String student[] = new String[maxStudents];
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(\"grade_in.txt\"));
while ((sCurrentLine = br.readLine()) != null) { // read line
String[] grd = sCurrentLine.split(\":\"); // split based on :
if(grd.length>1){ // if has grades
count++;
String gr = grd[1];
double gp = getgpa(gr.substring(0,gr.length()-1)); // get gpa score of grades
sum[index] = sum[index]+gp; // add to sum
}
else if(sCurrentLine.indexOf(\"--\")!=-1){ // new student
sum[index] = sum[index]/count;
count = 0;
index++;
}
else{
student[index] = sCurrentLine; // add student name to array
}
}
sum[index] = sum[index]/count; // for last variable.
File file = new File(\"GPA_out.txt\");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for(int i=0;i<=index;i++){
bw.write(student[i]+\"-\"+sum[i]+\"\ \"); // write to file
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static double getgpa(String s){
if(s.equals(\"A\"))
return 4.0;
else if(s.equals(\"A-\"))
return 3.7;
else if(s.equals(\"B+\"))
return 3.3;
else if(s.equals(\"B\"))
return 3;
else if(s.equals(\"B-\"))
return 2.7;
else if(s.equals(\"C+\"))
return 2.3;
else if(s.equals(\"C\"))
return 2;
else if(s.equals(\"C-\"))
return 1.7;
else if(s.equals(\"D+\"))
return 1.3;
else if(s.equals(\"D\"))
return 2;
else if(s.equals(\"D-\"))
return 0.7;
return 0;
}
}
/*
Tom-3.2
Tim-2.2
Smith-2.3400000000000003
Davis-2.6
Baker-2.6
*/

