Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Reads a file of exam scores and calculates the average score.
- */
- import java.io.FileReader;
- import java.io.FileNotFoundException;
- import java.util.Scanner;
- import java.io.PrintWriter;
- public class ExamAverage
- {
- public static void main(String[] args)
- throws FileNotFoundException
- {
- String inputFileName = "scores.txt";
- String outputFileName = "examScoreAverage.txt";
- FileReader fr = new FileReader(inputFileName);
- PrintWriter writer = new PrintWriter(outputFileName);
- try
- {
- int itterator = 0;
- int total = 0;
- String grade = "";
- while(true)
- {
- int ch = fr.read();
- if(ch == -1)
- {
- writer.println(String.format("Score %d: %.1f",++itterator , Float.parseFloat(grade)));
- total += Integer.parseInt(grade);
- break;
- }
- else if((char)ch == '\n')
- {
- writer.println(String.format("Score %d: %.1f",++itterator , Float.parseFloat(grade)));
- total += Integer.parseInt(grade);
- grade = "";
- }
- else if(Character.isDigit((char)ch))
- {
- grade += (char)ch;
- }
- }
- writer.println(String.format("Number of scores read: %d", itterator));
- writer.println(String.format("Average Score: %.1f", (float)((float)total / (float)itterator)));
- }
- catch(Exception e){}
- try
- {
- fr.close();
- writer.close();
- }
- catch(Exception e){}
- }
- }
Add Comment
Please, Sign In to add comment