advictoriam

Untitled

Mar 13th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. /**
  2.    Reads a file of exam scores and calculates the average score.
  3. */
  4.  
  5.  
  6. import java.io.FileReader;
  7. import java.io.FileNotFoundException;
  8. import java.util.Scanner;
  9. import java.io.PrintWriter;
  10.  
  11. public class ExamAverage
  12. {
  13.    public static void main(String[] args)
  14.       throws FileNotFoundException
  15.    {
  16.       String inputFileName = "scores.txt";
  17.       String outputFileName = "examScoreAverage.txt";
  18.      
  19.       FileReader fr = new FileReader(inputFileName);
  20.       PrintWriter writer = new PrintWriter(outputFileName);
  21.      
  22.       try
  23.       {
  24.          
  25.          int itterator = 0;
  26.          int total = 0;
  27.          String grade = "";
  28.          while(true)
  29.          {
  30.             int ch = fr.read();
  31.          
  32.             if(ch == -1)
  33.             {
  34.                writer.println(String.format("Score %d: %.1f",++itterator , Float.parseFloat(grade)));
  35.                total += Integer.parseInt(grade);
  36.                break;
  37.             }
  38.             else if((char)ch == '\n')
  39.             {
  40.                writer.println(String.format("Score %d: %.1f",++itterator , Float.parseFloat(grade)));
  41.                total += Integer.parseInt(grade);
  42.                grade = "";
  43.             }
  44.             else if(Character.isDigit((char)ch))
  45.             {
  46.                grade += (char)ch;
  47.             }
  48.          }
  49.          writer.println(String.format("Number of scores read: %d", itterator));
  50.          writer.println(String.format("Average Score: %.1f", (float)((float)total / (float)itterator)));
  51.       }
  52.       catch(Exception e){}
  53.      
  54.       try
  55.       {
  56.          fr.close();
  57.          writer.close();
  58.       }
  59.       catch(Exception e){}
  60.    }
  61. }
Add Comment
Please, Sign In to add comment